Control structures

Programming languages provide structures for executing instructions conditionally and/or repeatedly.

Branching and conditional execution: "if"

Here is the simplest version with branching. Note the ":" at the end of the if line and the else:, and also notice the indentation. Uniquely in Python, indentation identifies a block of code to be executed as a unit. Always use 4 spaces for each level of indentation. The IPython notebook helps you do this automatically.

When using a text editor to write Python code directly to a text file, you might need to configure the editor to insert 4 spaces when you press the Tab key, and to strip space characters from the ends of lines when the file is written to disk. Python itself is not so fussy about these things, but attending to them will make other important coding tools work much better.

In [1]:
a = 5
if a > 4:
    print("big")
else:
    print("small")
big

There can be more than one option:

In [2]:
a = 5
if a <= 0:
    print("zilch")
elif a < 5:
    print("small")
elif a == 5:
    print("just right")
else:
    print("too big")
just right

Notice that Python uses elif where some languages use "elseif" and others use "else if".

More importantly, notice that the indented block needs no "end" marker--it ends where the indentation ends. What you see is what you get!

Looping: "for" and "while"

A "for" loop also involves a line ending in a colon, and an indented block:

In [3]:
months = ["January", "February", "March", "April", "May"]
for m in months:
    print(m[:3])
Jan
Feb
Mar
Apr
May

In [4]:
for x in range(10, 50, 10):
    print("x is %d so x**2 is %d" % (x, x ** 2))
x is 10 so x**2 is 100
x is 20 so x**2 is 400
x is 30 so x**2 is 900
x is 40 so x**2 is 1600

We introduced some string formatting syntax there: each "%d" in the string is replaced with a matching integer from the tuple to the right of the final percent sign. More about this later; for now, the main point is that

for x in y:
    print x ** 2

simply iterates over the elements in y. In the example above, the Python built-in range() function returns a list (python 2) or an iterator (python 3), so the loop is over the elements of that list, or the items returned sequentially by the iterator.

Sometimes one wants to keep executing a block of code until a condition is met. This is done with a while loop:

In [5]:
x = 1
while x < 100:
    print(x)
    x = x + x ** 2
1
2
6
42

Loops and branching often work together. The break statement brings an immediate exit from a loop, and a continue statement skips the remainder of a loop block and jumps to the next iteration of the loop.

In [6]:
for x in range(3, 20):
    if x % 2 == 1:
        print("odd number; try the next one")
        continue
    print("even: ", x)
    if x ** 2 > 60:
        print("x ** 2 is too big; we quit here")
        break
odd number; try the next one
even:  4
odd number; try the next one
even:  6
odd number; try the next one
even:  8
x ** 2 is too big; we quit here

There is also a pass statement which means "do nothing". We will see it in a later notebook when we introduce Exceptions.

In [6]: