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
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
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")
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"
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.