-4
a = raw_input("please type 1 or 0")
while a != 0 or 1:
    print"please retype"
    a = raw_input("please type 1 or 0")
print "thanks"

I don't know why my output always repeats line 3 and 4 no matter what figure I typed in. Thank you

gyre
  • 16,369
  • 3
  • 37
  • 47
Josh Yang
  • 5
  • 2
  • Condition in `while` always is `True`. – Dmitry Apr 19 '17 at 14:52
  • 4
    `while a != 0 or a !=1:` is needed. `1` is always true. Edit: actually a cant be both 1 and 0, so it's always either not 0 or not 1, so what you're looking for is probably `while a!=0 and a!=1` – 098799 Apr 19 '17 at 14:53
  • 1
    `raw_input` returns a string, you need to cast to `int` – roganjosh Apr 19 '17 at 14:53
  • You could try `while a not in (0, 1):` – Laurent G Apr 19 '17 at 14:54
  • 2
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Chris_Rands Apr 19 '17 at 14:54
  • 2nd part of dupe: http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values – Chris_Rands Apr 19 '17 at 14:55
  • Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – gyre Apr 19 '17 at 14:59

3 Answers3

2

a != 0 or 1 is actually interpreted as (a != 0) or (1), where the expressions enclosed in parentheses are evaluated as booleans. Since 1 is always True, the while loop continues to run forever, irrespective of the value of a.

See the near-duplicate How do I test one variable against multiple values? for more information on why the or operator does not serve the purpose you might expect in this situation.

You should use strings in your condition, since raw_input returns a string, and check whether a is one of several possibilities using the not in operator and a tuple:

a = raw_input("please type 1 or 0")
while a not in ('1', '0'):
    print("please retype")
    a = raw_input("please type 1 or 0")
print("thanks")
gyre
  • 16,369
  • 3
  • 37
  • 47
0

Just another example:

a = raw_input("please type 1 or 0\n")
while True:
    if a in ("1", "0"):
        break
    print "please retype"
    a = raw_input("please type 1 or 0\n")
print "thanks"
zipa
  • 27,316
  • 6
  • 40
  • 58
0

You could use a helper variable to determine if the criteria are met.

b = True
while b:
    a = input("please type 1 or 0")
    if a == "0" or a == "1":
        b = False
    else:
        print("please retype")

print("thanks")

This also prevents non integer characters from throwing an error.

Superspork
  • 393
  • 2
  • 9