0

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
asked Oct 27, 2019 at 18:28

1 Answer 1

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
answered Oct 27, 2019 at 18:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.