Add A Loop Until User Inputs A Valid Answer?
I want to add a loop to this: question = raw_input('Reboot Y/N ') if len(question) > 0 and question.isalpha(): answer = question.upper() if answer == 'Y': print
Solution 1:
Add a while True at the top, and if user has entered correct output, break the loop: -
whileTrue:
question = raw_input("Reboot Y/N ")
iflen(question) > 0:
answer = question.upper()
if answer == "Y":
print"Reboot"breakelif answer == "N":
print"Reboot Canceled"breakelse:
print"/ERROR/"
Solution 2:
something like this:
answer={"Y":"Reboot","N":"Reboot cancled"} #use a dictionary instead of if-else
inp=raw_input("Reboot Y/N: ")
while inp not in ('n','N','y','Y') : #use a tuple to specify valid inputsprint"invalid input"
inp=raw_input("Reboot Y/N: ")
print answer[inp.upper()]
output:
$pythonso27.pyReboot Y/N:fooinvalidinputReboot Y/N:barinvalidinputReboot Y/N:yReboot
Post a Comment for "Add A Loop Until User Inputs A Valid Answer?"