Validating user input strings in Python
Solution 1:
You are testing if the user input is yes
or no
. Add a not
:
while userInput not in ['yes', 'no']:
Ever so slightly faster and closer to your intent, use a set:
while userInput not in {'yes', 'no'}:
What you used is userInput in ['yes', 'no']
, which is True
if userInput
is either equal to 'yes'
or 'no'
.
Next, use a boolean to set endProgram
:
endProgram = userInput == 'no'
Because you already verified that userInput
is either yes
or no
, there is no need to test for yes
or no
again to set your flag variable.
Solution 2:
def transaction():
print("Do the transaction here")
def getuserinput():
userInput = "";
print("Start")
while "no" not in userInput:
#Prompt for a new transaction
userInput = input("Would you like to start a new transaction?")
userInput = userInput.lower()
if "no" not in userInput and "yes" not in userInput:
print("yes or no please")
if "yes" in userInput:
transaction()
print("Good bye")
#Main program
getuserinput()