Simplest form:
if expression: body
expression
expression
's value is True
,
then execute body
body
General form:
if expression1: body1 elif expression2: body2 # ... elif expressionN: bodyN else: body
expression1
expression1
's value is True
,
then execute body1
expression2
expression2
's value is True
,
then execute body2
expressionN
expressionN
's value is True
,
then execute bodyN
body
expression2
is evaluated ONLY
if expression1
's value was False
,
and similarly for all other expressions—
in particular, the final body
is executed only if
every expression
evaluated to False
Compare:
if sunny: print("It's lovely out!") elif warm: print("At least it's not cold.")
with:
if sunny: print("It's lovely out!") if warm: print("At least it's not cold.")
my_average >= 90This is a boolean expression: its value is of type
bool
.>=
is a boolean operator:
it takes two operands and gives a bool
back.
3 < 4 3 > 8 8 > 3 3.5 >= 3.5 7 == 7 # Why not just one equals sign? x == 7 y == 7.0 x == y 3 != 4
snowing = False # The basic boolean values need a capital sunny = True not snowing # "not" is a unary operator: 1 operand not sunny sunny and snowing # "and" and "or" are binary operators: 2 operands sunny or snowing a = False b = True not a or b # precedence? (not a) or b not (a or b) # "not" has priority: it's like "-" -3 + 7 (-3) + 7 -(3 + 7) not not a # double negative not not not a # or more
x < 0 or x > 100
0 < x <= 20is a shorthand for
0 < x and x <= 20NOTE: The original version of these notes mistakenly used
or
instead of and
to combine the two
inequalities— and
is the correct operator
False
is stored internally as 0
,
and True
as 1
, but
you should never need to use this directly
True
by using it in an if
-statement
not not a
;
a
is much clearer
# Suppose you have a boolean variable below_zero. if below_zero == True: print("Brrrr!") # That was analogous to saying: if (temperature < 0) == True: # Obviously silly, but equivalent! print("Brrr!") # below_zero is already a boolean (just like "temperature < 0"); # there's no need to make it into one. This is simpler: if below_zero: print("Brrr!")
def is_odd(x): if x % 2 == 1: return True else: return Falsecan be much simplified:
def is_odd(x): return x % 2 == 1