Python Control Flow

if Statements

Example 1

if x < 0:
    x = 0
    print 'Negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'Single'
else:
    print 'More'

Example 2: Emulating ?:
x ? y : z will be written in Python:

if x 
    x = z
else 
    y = z

Another way:We create a small list constant, containing the two values to choose from, and use the boolean as an index into the list. "False" is equivalent to 0 and will select the first element, while "True" is equivalent to 1 and will select the second one.

[z, y][bool(x)]

for Statements

  • In Python the for statement iterates over the items of any sequence, in the order that they appear in the sequence.

Example

a = ['cat', 'window', 'defenestrate']
for x in a:
    print x, len(x)
  • One difference from C is in the for loop, which can be applied to any "iterable" object:
>>> str = "foo"; lst = ["abra", 2038, "cadabra"]
>>> for char in str:
...     print char
... 
>>> for elem in lst:
...     print elem
...

The range() Function

  • To iterated over a sequence of numbers the built-in function range() can be used.
  • One argument means up to that number: range(10)
  • Two arguments mean the start and end number: range(1,10)
  • Three arguments mean the start, the end and the step number: range(1,10,2)

Example 1

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]

Example 2: he following example demonstrates a so-called generator function. It can be used as an iterable object which creates its objects on the fly.

>>> def iterquad ():
...     for i in range(5):
...         yield (i*i)
... 
>>> for j in iterquad():
...     print j
...

break and continue Statements and else Clauses on Loops

  • The break statement breaks out of the smallest enclosing for or while loop.
  • The continue statement, continues with the next iteration of the loop.
  • Loop statements may have an else clause. It is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while).

Example

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
...

pass Statements

  • The pass statement does nothing. It is used when a statement is required syntactically but the program requires no action.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.