Conditional statements with if

From Training Material
Jump to navigation Jump to search

Conditional statements with if

If statements are used to implement decisions and branching in the program. They must contain an 'if' block, and optionally one or many 'elif' and an 'else' block:

if fruit == 'apple':
price = 0.55
elif fruit == 'banana':
price = 0.75
elif fruit == 'orange':
price = 0.80
else:
print 'we dont have %s'%(fruit)

Boolean value of variables

Each variable can be interpreted as boolean logic. All values are treated as True, except for:

False
0
[]
''
{}
None

Code blocks

  • After an if statement, all indented commands are treated as a code block, and are executed if the condition applies.
  • The next unindented command Is executed in any case.

Comparison operators

An expression may contain any combination of:

  • a == b, a != b (equality)
  • a < b, a > b, a <= b, a >= b (relations)
  • a or b, a and b, not a (boolean logic)
  • (a or b) and (c or d) (priority)
  • a in b (inclusion, when b is a list)