Programming languages provide structures for executing instructions conditionally and/or repeatedly.
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.
a = 5
if a > 4:
print("big")
else:
print("small")
There can be more than one option:
a = 5
if a <= 0:
print("zilch")
elif a < 5:
print("small")
elif a == 5:
print("just right")
else:
print("too big")
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!
A "for" loop also involves a line ending in a colon, and an indented block:
months = ["January", "February", "March", "April", "May"]
for m in months:
print(m[:3])
for x in range(10, 50, 10):
print("x is %d so x**2 is %d" % (x, x ** 2))
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:
x = 1
while x < 100:
print(x)
x = x + x ** 2
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.
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
There is also a pass
statement which means "do nothing". We will see it in a later notebook when we introduce Exceptions.