Python Flow Control

The if statement:

``````if x < 0:
print "Negative"
elif x == 0:
print "Zero"
elif x == 1:
print "Single"
else:
print "More"```
```

The for statement:

It is not safe to modify the sequence being iterated over in the loop. If you need to modify the list you are iterating over you must iterate over a copy. The slice notation makes this particularly convenient:

``````for x in a[:]: # make a slice copy of the entire list
if len(x) > 6: a.insert(0, x)```
```

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions:

````range(10)  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`
```

The given end point is never part of the generated list. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):

``````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]```
```

To iterate over the indices of a sequence, you can combine range() and len() as follows:

``````a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]```
```

In most such cases, however, it is convenient to use the enumerate() function.

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), but not when the loop is terminated by a break statement.

The pass statement:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. This is commonly used for creating minimal classes such as exceptions, or for ignoring unwanted exceptions.

Define a function:

````def fib(n):`
```

The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented. The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring. It’s good practice to include docstrings in code that you write, so make a habit of it.

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.

A function definition introduces the function name in the current symbol table. The value of the function name has a type that is recognized by the interpreter as a user-defined function. This value can be assigned to another name which can then also be used as a function. This serves as a general renaming mechanism:

``````def fib(n):
blah
f = fib```
```

Function without a return statement, returns None. Writing the value None is normally suppressed by the interpreter if it would be the only value written. You can see it if you really want to using print.

````def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):`
```

The default values are evaluated at the point of function definition in the defining scope, so that:

``````i = 5

def f(arg=i):
print arg

i = 6
f()```
```

will print 5.

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

``````def f(a, L=[]):
L.append(a)
return L

print f(1)
print f(2)
print f(3)```
```

This will print

``````[1]
[1, 2]
[1, 2, 3]```
```

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

``````def f(a, L=None):
if L is None:
L = []
L.append(a)
return L```
```

Functions can also be called using keyword arguments of the form keyword = value. For instance, the following function:

````def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):`
```

could be called in any of the following ways:

``````parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')```
```

but the following calls would all be invalid:
``````parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument following keyword
parrot(110, voltage=220)     # duplicate value for argument
parrot(actor='John Cleese')  # unknown keyword```
```

In general, an argument list must have any positional arguments followed by any keyword arguments, where the keywords must be chosen from the formal parameter names. It’s not important whether a formal parameter has a default value or not. No argument may receive a value more than once — formal parameter names corresponding to positional arguments cannot be used as keywords in the same calls.

When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.) For example, if we define a function like this:

``````def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, "?"
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print "-" * 40
keys = keywords.keys()
keys.sort()
for kw in keys: print kw, ":", keywords[kw]```
```

It could be called like this:

``````cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper='Michael Palin',
client="John Cleese",
sketch="Cheese Shop Sketch")```
```

and of course it would print:

``````-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch```
```

Note that the sort() method of the list of keyword argument names is called before printing the contents of the keywords dictionary; if this is not done, the order in which the arguments are printed is undefined.

Arbitrary Argument Lists:
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more normal arguments may occur.

``````def write_multiple_items(file, separator, *args):
file.write(separator.join(args))```
```

Unpacking Argument Lists:
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

``````>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]```
```

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

``````>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !```
```

Lambda:

With the lambda keyword, small anonymous functions can be created. Here’s a function that returns the sum of its two arguments: lambda a, b: a+b. Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:

``````>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43```
```
page revision: 4, last edited: 10 Dec 2008 19:21