I need for user to enter a correct format of pin. So i made a code that is supposed to do that.
def checkPin():
pin = input("Please enter pin: ")
if len(pin) > 6 or len(pin) < 6:
print("Error only 6 characters allowed")
checkPin()
if pin.isdigit()==False:
print("Error only numbers allowed")
checkPin()
checkPin()
print("Entered correct format pin")
Then i enter an incorrect pin i get an error, so it gives me another try to enter a good format pin. Then i enter a good format pin it gives me an error, but then i enter the same good format pin like i entered in second try i don't get an error.I don't understand why it happens. Here is the output:
Please enter pin: abc
Error only 6 characters allowed
Please enter pin: 123456
Error only numbers allowed
Please enter pin: 123456
Entered correct format pin
1 Answer 1
When the first recursive call to checkPin returns, you are checking the first input abc for digits, not the number entered in the recursive call.
If you use return checkPint(), you'll avoid unnecessarily checking the original bad input again.
def checkPin():
pin = input("Please enter pin: ")
if len(pin) > 6 or len(pin) < 6:
print("Error only 6 characters allowed")
return checkPin()
if pin.isdigit()==False:
print("Error only numbers allowed")
return checkPin()
or use elif
def checkPin():
pin = input("Please enter pin: ")
if len(pin) > 6 or len(pin) < 6:
print("Error only 6 characters allowed")
checkPin()
elif pin.isdigit()==False:
print("Error only numbers allowed")
checkPin()
However, you shouldn't use recursion at all simply to implement a loop.
def checkPin():
while True:
pin = input("Please enter pin: ")
if len(pin) > 6 or len(pin) < 6:
print("Error only 6 characters allowed")
elif pin.isdigit()==False:
print("Error only numbers allowed")
else:
break