Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using both OR, AND in an IF-statement - Python

Tags:

python

def alarm_clock(day, vacation):
    if day == 0 or day == 6 and vacation != True:
        return "10.00"
    else: 
        return "off"

print(alarm_clock(0, True))

Why does this return "10.00"? In my mind it should return "off". Yes, day is equal to 0, but vacation is True, and the IF-statements first line states that it should only be executed if vacation is not True.

like image 328
Marty Avatar asked Aug 24 '26 14:08

Marty


1 Answers

In Python and binds tighter than or. So your statement is equivalent to this:

if day == 0 or (day == 6 and vacation != True):

To get the correct result you must parenthesize the precedence yourself:

if (day == 0 or day == 6) and vacation != True:
like image 60
orlp Avatar answered Aug 27 '26 02:08

orlp