Python Forum

Full Version: How to use -> or
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!")
(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!")
Normally you would use "while not num in ['1', '2']:"

The answer to your question is "or" doesn't do what you think it does.
Output:
>>> ("1" or "2") '1'
"or" works left to right, evaluating conditions and stopping as soon as the result of "or" does not evaluate to False. In the example above "or" first looks at "1", "1" is not an empty string, so it is not False. Since "or" encountered a value that is not false, it is done evaluating and returns the result, "1".

This may be a better demonstration:
Output:
>>> "a" or a 'a' >>> a or "a" Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> a or "a" NameError: name 'a' is not defined
I do not have a variable named 'a', so trying to evaluate anything involving 'a' will result in a NameError. The first example does not crash because the "or" stops evaluating prior to using 'a'. The second example crashes even though it looks like it does exactly the same thing.
OMG! thank you!! it helped me a lot
just to provide links to relevant parts of the docs:
Truth value testing
Boolean operations - and, or, not