Jump to content

why wont this work? (python using or in an if statemt)

Go to solution Solved by Alvin853,

That's not how 

or

works. The == takes precedence over the or, so 

total == 1 or 2

evaluates to 

(3 == 1) or 2 
false or 2

"or 2" doesn't mean anything to Python, so the 2 is converted to a boolean, which turns it into true, and true on any side of an "or" makes the whole thing true.

You need to write

total == 1 or total == 2

for it to work as expected

total = 3

def function():
    global total
    if total == 1 or 2:
        print(total)
        print("I'm a function that lets you know that your number is 1 or 2!")
    else:
        print("This is to let you know your number ISNT 1 or 2!")
        
def function_quotes():
    global total
    if total == "1" or "2":
        print(total)
        print("I'm a function that lets you know that your number is 1 or 2!")
    else:
        print("This is to let you know your number ISNT 1 or 2!")
            
function()
function_quotes()

 

obviously the expected outcome is that the else line will get executed instead of the if line

OUTDATED JAN 2021 ===========> Check out my pc building guide! might be useful tho

It's great for planning new builds, getting a reference on where to start, or seeing what you need to play what games.

It also shows what I recommend for upgrading your stuff!

cpu - ryzen 5 3600

gpu - gtx 1070

ram - (2x8) 3200mhz

ssd - 970 evo plus 500gb

ssd2 - 860 qvo 1tb

mobo - asrock b450m hdv r4.0

psu - evga b5 550w bronze

Link to post
Share on other sites

That's not how 

or

works. The == takes precedence over the or, so 

total == 1 or 2

evaluates to 

(3 == 1) or 2 
false or 2

"or 2" doesn't mean anything to Python, so the 2 is converted to a boolean, which turns it into true, and true on any side of an "or" makes the whole thing true.

You need to write

total == 1 or total == 2

for it to work as expected

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×