Conditional StatementsΒΆ

>>> if 1 > 3:
...     print "OOPS: 1 > 3?"
...     ok = False
... elsif []:
...     print "OOPS: Empty list not empty?"
...     ok = False
... elsif None:
...     print "OOPS: Nonesuch object not empty??"
...     ok = False
... else
...     print "OK"
...     ok = True
...
OK
  • In Python, indentation matters as it defines statement grouping:
>>> i = 1
... if i and (i == 1 or i == 2):
...   print "OK"
...
OK
>>> if i:
...     x = i + 1
...   y = x + 1
  File "<stdin>", line 3
    y = x+1
          ^
IndentationError: unindent does not match any outer indentation level
  • In the following case, y is updated unconditionally:
>>> if i:
...     x = i + 1
... y = x + 1
...