0

I need python to keep asking the raw_input if the answer is different from 1 or 2.

Here the example:

print """What do you want me to do?

1) Press 1 if you want to .....
2) Press 2 if you want to ....."""

while True:
    answer1 = raw_input(" => ")

    if (answer1 == 1):
        ....
        ....

    elif (answer1 == 2):
        ....
        ....

    elif (answer1 != 1 or 2) or answer1.isalpha():
        print "I need 1 or 2"

The problem is that python is keeping asking the raw_input also if the user enter 1 or 2. Where am I wrong?

benten
  • 1,995
  • 2
  • 23
  • 38
Francesco Mantovani
  • 10,216
  • 13
  • 73
  • 113
  • 2
    put a `break` in both the conditions when `answer == 1` and `answer == 2` in the end – shaktimaan Jul 02 '15 at 06:53
  • Your base condition `while True:` will never gets false so it will go in infinite loop. You should use the boolean `True` in some variable and make it false when your conditions gets `True`. – Tanveer Alam Jul 02 '15 at 06:54
  • set `answer1 = None` before the while loop and then the while loop should be `while answer1 != 1 and answer1 != 2:`. – Dobz Jul 02 '15 at 06:55
  • The duplicate does not address the `or` problem in this question. There are better duplicate targets. – Reut Sharabani Jul 02 '15 at 06:56

1 Answers1

0

You should put a break statement in the if and elif block if answer is 1 or 2 to break out of the while loop.

Example -

if (answer1 == 1):
    ....
    ....
    break
elif (answer1 == 2):
    ....
    ....
    break
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176