1

I need the choices to be asked again until the user chooses a valid option.

choice = input('Please choose 1,2,3\n')

if choice == 1:
print('You have chosen the first option')

elif choice == 2:
print('You have chosen the second option')

elif choice == 3:
print('You have chosen the third option')

else:
print('This is not an option, please try again.')
2
  • 1
    Have you learned about loops? You should learn about loops. Go do that. They are fundamental in almost any programming language. Commented Aug 3, 2015 at 22:37
  • 1
    read about while loops in python Commented Aug 3, 2015 at 22:37

3 Answers 3

2

Perhaps I am mistaken, as I am just a hack, but I believe a more "Pythonic" answer would be:

choices = {1:'first', 2:'second', 3:'third'}

while True:
    choice = input('Please choose 1, 2, or 3.\n')
    try:
        print 'You have chosen the {} option.'.format(choices[choice])
        break
    except KeyError:
        print 'This is not an option; please try again.'

Or at least:

while True:
    choice = input('Please choose 1, 2, or 3.\n')

    if choice == 1:
        print 'You have chosen the first option'
        break
    elif choice == 2:
        print 'You have chosen the second option'
        break
    elif choice == 3:
        print 'You have chosen the third option'
        break
    else:
        print 'This is not an option; please try again.'

Both of these avoid creating an unnecessary test variable, and the first one reduces overall code needed.

For Python 3, I believe adding parentheses around the printed statements should be the only change. The question wasn't tagged with a version.

Sign up to request clarification or add additional context in comments.

5 Comments

Like this, but I'd suggest use of if int(choice) in choices: print 'You have chosen the {} option.'.format(choices[choice]) -- '1', '2', and '3' can be strings in the choices dict too, saving some trouble with converting to int.
I'd include an option 'q' for 'quit'. Pleasanter for users who aren't sophisticated enough to Ctrl-C out, and if you hook the logic into a GUI, you already have something for the Cancel button.
@ap, I used to always do it that way too, but I seem to remember coming across an explanation that for large dictionaries, it was less efficient. I realize that, in this case, it's trivial, but I got in the habit of catching the KeyError instead. Upon further inspection, it looks like it depends, with your approach just edging mine out based on clarity.
@Tom it's possible, but I can't imagine how either way would be less efficient. Checking membership in a hash (dict) is O(1) -- very fast, even on large data sets. And in order to throw a KeyError, the work of looking something up needs to be done anyway.
@Tom I'd argue about Pythonic. Using dictionary as choice-chooser is cool but it's also considered a replacement for switch-case. I'd also use dict.
0

Try this:

valid = False
while(valid == False):

   choice = input("Please choose 1,2,3\n")

   if choice == 1:
      valid = True
      print('You have chosen the first option')

   elif choice == 2:
     valid = True
     print('You have chosen the second option')

   elif choice == 3:
     valid = True
     print('You have chosen the third option')

   else:
     valid = False
     print('This is not an option, please try again.')

6 Comments

Used to C/C++ structuring so I had to think twice for python
It says that 'false' is not defined
Try capitalizing False and True
You keep entering code that is either wrong or entirely invalid Python syntax.
As far as I'm aware, testing your code to make sure it compiles and runs as expected is just as important in C/C++ as it is in Python.
|
0

You could make it into a function, which takes the required prompt, valid selections and only returns when a valid input is made.

def get_input(prompt, choices):
    while True:
        choice = input("%s %s or %s: " % (prompt, ", ".join(choices[:-1]), choices[-1]))
        if str(choice) in choices:
            return choice

choice = get_input("Please choose", ["1", "2", "3"])
print("You have chosen {}".format(choice))

Which would give the following type of output:

Please choose 1, 2 or 3: 1
You have chosen 1

Comments

Your Answer

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.