Home > Blockchain >  Using both OR, AND in an IF-statement - Python
Using both OR, AND in an IF-statement - Python

Time:06-27

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.

CodePudding user response:

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:

CodePudding user response:

What you probably want is this:

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))
  • Related