Jan-11-2021, 03:28 PM
(Jan-11-2021, 02:59 PM)Flora_The_Pious Wrote: Im trying to figure out why "1" get me out of the loop but "2" doesnt. (started learning coding 2 days ago.)
num = input("answer:")
while not num == ("1" or "2"):
print("ERROR")
num = input("answer:")
else:
print("GOOD!")
Because '("1" or "2")' is considered to be a logical expression and thus always is "1" or True. In Python all logic expressions evaluate the first part "1", which is considered to be True, so "2" is never evaluated.
A good rule to remember about logical expressions (in Python) is that
'if A or B' logically can be seen as 'if A then True else B'
and
'if A and B' can be seen as 'if A then B else False'
So the second (and third and ...) expression is evaluated only if a conclusive value has not yet been calculated.
I guess that you want to achieve is a test on the numbers:
num = input("answer:") while not (num == "1" or num == "2"): print("ERROR") num = input("answer:") else: print("GOOD!")which is the same as:
num = input("answer:") while not num in ("1", "2"): print("ERROR") num = input("answer:") else: print("GOOD!")or
num = input("answer:") while num not in ("1", "2"): print("ERROR") num = input("answer:") else: print("GOOD!")or, if it is numbers you are testing
num = int(input("answer:")) while num not in (1, 2): print("ERROR") num = int(input("answer:")) else: print("GOOD!")