I am trying to run a section of code with a bunch of "selection criteria" but I've run into a wall.
This is the code:
phone= int(input("Enter phone number : "))
if len(str(phone)) != 10 or str(phone)[:2] != "04":
print("Invalid format. Try again.")
else:
print("Thanks queen!")
However, no matter what input, the output is always
Invalid format. Try again.
What am I doing wrong?
CodePudding user response:
Despite the name, phone numbers are not numbers, they're identifiers (sometimes with superfluous formatting). Your initial conversion of the input to integer is the root of your subsequent problems. The conversion from integer back to string would never result in a leading zero so str(phone)[:2] != "04"
will always evaluate to True
.
Without the conversions it's cleaner and correct:
phone = input("Enter phone number : ")
if len(phone) != 10 or phone[:2] != "04":
print("Invalid format. Try again.")
else:
print("Thanks queen!")
You may want to clean the entered phone number directly after input to remove formatting characters:
phone = ''.join(filter(str.isdigit, phone))
CodePudding user response:
Yeah, converting "04" to a string throws a leading zero error. I tried it with converting an int with a non-leading zero and passed the condition to receive, "Thanks queen!"
phone = str(3214567890)
firstTwo = phone[:2]
expectedLen = 10
expectedFirstTwo = "32"
if len(phone) != expectedLen or firstTwo != expectedFirstTwo:
print("Invalid format. Try again.")
else:
print("Thanks queen!")