-3

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 "Reboot"
    elif answer == "N":
        print "Reboot Cancled"
    else:
        print "/ERROR/"

So if the user inputs anything else the error appears and sends them back to the question.

martineau
  • 119,623
  • 25
  • 170
  • 301
Molly
  • 19
  • 1
  • 1
  • You realize that if the user types anything other than a letter, he's not going to get any response at all, right? Is that what you intended? – abarnert Nov 28 '12 at 19:11
  • 2
    Why is this so heavily downvoted and closed? This seems like a common beginner question. – ShreevatsaR Oct 20 '13 at 11:32
  • Canonical duplicate: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – tripleee Feb 11 '21 at 10:04

2 Answers2

6

Add a while True at the top, and if user has entered correct output, break the loop: -

while True:
    question = raw_input("Reboot Y/N ")
    if len(question) > 0:
        answer = question.upper()
        if answer == "Y":
            print "Reboot"
            break
        elif answer == "N":
            print "Reboot Canceled"
            break
        else:
            print "/ERROR/"
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

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 inputs
   print "invalid input"
   inp=raw_input("Reboot Y/N: ")

print answer[inp.upper()]   

output:

$ python so27.py

Reboot Y/N: foo
invalid input
Reboot Y/N: bar
invalid input
Reboot Y/N: y
Reboot
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504