Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use -> or
#2
(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!")
Reply


Messages In This Thread
How to use -> or - by Flora_The_Pious - Jan-11-2021, 02:59 PM
RE: How to use -> or - by Serafim - Jan-11-2021, 03:28 PM
RE: How to use -> or - by deanhystad - Jan-11-2021, 03:29 PM
RE: How to use -> or - by Flora_The_Pious - Jan-11-2021, 03:34 PM
RE: How to use -> or - by buran - Jan-11-2021, 03:36 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020