Python
Flow Control
Your program can take different paths based on the
data it works with
There are a couple ways to make decisions but
the most common way is to use variations of the if statement
An if statement evaluates a Boolean expression
A Boolean expression evaluates to True or False
If the expression evaluates to True, the indented block of code following the if statement is executed
Otherwise, it is not
By using elif and else clauses, you can further customize its behavior
First variation: a single if clause
>>> age = 18
>>> if age >=
18:
...���� print 'you can vote'
you can vote
This �works,� in that �you can vote� prints
successfully given that age has been assigned 18
But if age were assigned a value less than 18,
nothing would print
>>> age = 17
>>> if age >=
18: # for age==17, this evaluates� to
False
...���� print 'you can vote' # and this line does not exectute
(No printed output appears)
You probably would like to know what happens
if the voter�s age is less than 18
An if�else structure works
great for binary (yes/no, true/false) types of decision making
The following example uses an else clause in addition to if
An else clause does not take a conditional
expression
An else clause only
executes when the expression in the if clause evaluates
to False
>>> age = 17
>>> # if age is assigned 17, the following
evaluates to False
>>> if age >=
18:
...���� # and
this line does not execute
...���� print 'you can vote'
... else:
...���� # but
this line does!������������������
...���� print 'you cannot vote'
...
you cannot vote
Sometimes a binary decision won�t do�you need if�elif�else
In this variation, we start with an if clause, followed by any number of elif clauses, followed optionally by a single else clause
All of the if and elif clauses evaluate Boolean expressions
elif is short for �else if�
The indented code following the first
expression that evaluates to True is executed
The rest of the clauses are ignored
The final else is only executed
if all the previous expressions evaluate to False
This example shows how to use this type of
decision making structure (try this out in an editor�the command line is too
painful):
if age >= 16 and
age < 17:
�� print 'you can drive with a permit'
elif age >= 17 and
age <= 90:
�� print 'you can drive with a license'
elif age > 90:
�� print 'please think twice about driving'
else:
�� print 'you are not qualified to drive'
Loops
All useful programming languages implement one
or more types of loops
Loops let you repeatedly perform a block of
code
There are many reasons why you would want to
do this
for loop
A for loop is useful
when the starting and ending conditions for looping are well known
Here is a simple example:
for x in range(0, 5):
�� print x
Let�s look at the pieces:
for |
x |
in |
range(0,5): |
keyword |
variable |
keyword |
method defining start and end |
When the loop runs, x takes on a value in the range 0 to 5, incrementing x by 1 through the list
The first number in the range() function defines the starting assignment for x (or whatever variable name we choose)
The second number is the ending condition�it
tells the loop to stop when x equals or exceed this
condition
We can use the value of x for printing, calculations�you name it
Here is a slightly more complicated example that
prints a table of squares:
print 'x', 'x squared'
for x in range(0, 5):
�� print x, x**2
And something yet more complicated�print a
degrees to radians table
Here we use range()
with 3 arguments
The third is the step�the increment between
values of our variable
We use it to specify the spacing between
degree increments in the table
Try changing it to other values
import numpy� # make
functions in the numpy module available here
�������������
# NOTE: the math module contains similar methods
print 'deg', '\t', 'rad' # '\t' prints a tab character
for theta in range(0,
360, 45): # the third argument in range is the step
�� if len(str(theta))
< 3: # use 2 tabs after 1 and 2 digit deg numbers
���� tabs = '\t\t'
�� else:
���� tabs = '\t'� # use 1
tab after numbers with 3 or more digits
�� print theta, tabs, numpy.deg2rad(theta) # convert degrees to
radians
Real Python programmers don�t use for loops!
Instead, they replace it (when possible) with
something called a list comprehension
Try this:
print range(0, 5)
This is the list that your
for loop used invisibly
Now try this:
print [x**2 for x in
range(0, 5)]
A list comprehension creates another list, in
this case, one in which each original x has been squared
List comprehensions are extremely common in
Python programming because they generally run faster than equivalent for loops
We will look at list comprehensions in another
lecture
while loop
Although they exist in Python, while loops are used much less than for loops
Here is our degrees/radians table again:
theta = 0 �� # our looping variable
print 'deg', '\t', 'rad' # '\t' prints a tab character
while theta <
360:� # our loop ending condition
�� if len(str(theta))
< 3: # use 2 tabs after 1 and 2 digit deg numbers
���� tabs = '\t\t'
�� else:
���� tabs = '\t'
�� print theta, tabs, numpy.deg2rad(theta)
�� theta += 45��� #
remember to increment theta!
Too many places to make mistakes�you can
usually do the same thing, easier, with a for loop
����