Programming with Python
Repeating Actions with Loops and Making Choices
Learning Objectives
- Explain what a for loop does.
- Correctly write for loops to repeat simple calculations.
- Trace changes to a loop variable as the loop runs.
- Trace changes to other variables as they are updated by a for loop.
- Write conditional statements including if, elif, and else branches.
- Correctly evaluate expressions containing
and
andor
. - Combine loops and conditionals into longer programs.
Deep down, most people want to learn how to program so they can automate the things they don’t want to do themselves. To do that, we’ll have to teach the computer how to repeat actions.
For example, we might need to access each item in a list. One way to do this would be to use a series of print statements:
odds = [1, 3, 5, 7]
print odds[0]
print odds[1]
print odds[2]
print odds[3]
1
3
5
7
This is a bad approach for two reasons:
It doesn’t scale: if we want to print the characters in a string or the items in a list that’s hundreds of values long, it would take a very, very long time.
It’s fragile: if we replace the list of odd values above with a longer list, it will only print part of the data, and if we give it a shorter list, it produces an error because we’re asking for values that don’t exist.
odds = [1, 3, 5]
print odds[0]
print odds[1]
print odds[2]
print odds[3]
1
3
5
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-20-543712197ba5> in <module>()
3 print odds[1]
4 print odds[2]
----> 5 print odds[3]
IndexError: list index out of range
A better approach is to automate the task with a for loop:
word = 'lead'
for char in word:
print char
l
e
a
d
This is shorter than writing individual print statements for each character, and more robust as well:
word = 'oxygen'
for char in word:
print char
o
x
y
g
e
n
The improved version of our script uses a for loop to repeat an operation — in this case, printing — once for each item in a collection. The general form of a for loop is:
for variable in collection:
do things with variable
We can call the loop variable anything we like, but there must be a colon at the end of the line starting the loop and we must indent anything we want to run inside the loop. Unlike many other languages, there is no command to end a loop (e.g. end); what is indented after the for statement belongs to the loop.
Here’s another loop that repeatedly updates a variable:
word = 'oxygen'
length = 0
for char in word:
length = length + 1
print 'There are', length, 'characters in the word', word
There are 6 characters in the word oxygen
It’s worth tracing the execution of this little program step by step. Since there are six characters in ‘oxygen’, the statement on line 4 will be executed six times. The first time around, length is zero (the value assigned to it on line 1) and char is ‘o’. The statement adds 1 to the previous value of length, producing 1, and updates length to refer to that new value. The next time around, char is ‘x’ and length is 1, so length is updated to be 2. After four more updates, length is 6; since there is nothing left in ‘oxygen’ for Python to access, the loop finishes and the print statement on line 5 tells us our final answer.
Note that a loop variable is just a variable that’s being used to record progress in a loop. It still exists after the loop is over, and it can be over-written like any other variable:
letter = 'z'
for letter in 'abc':
print letter
print 'after the loop, letter is', letter
a
b
c
after the loop, letter is c
Computing powers with loops
Exponentiation is built into Python:
print 5**3
125
Write a loop that calculates the same result as 5 ** 3
using just multiplication (without exponentiation).
Reverse a string
Write a loop that takes a string, and produces a new string with the characters in reverse order, so 'Newton'
becomes 'notweN'
.
Making Choices
When analyzing data, we’ll often want to automatically detect differences between values and take different actions on the data depending on some conditions. Here, we’ll learn how to write code that runs only when certain conditions are true.
Conditionals
We can ask Python to take different actions, depending on a condition, with an if statement:
num = 42
if num > 100:
print 'greater'
else:
print 'not greater'
print 'done'
not greater
done
The second line of this code uses the keyword if
to tell Python that we want to make a choice. If the test that follows the if statement is true, the body of the if (i.e., the lines indented underneath it) are executed. If the test is false, the body of the else is executed instead. Only one or the other is ever executed.
Conditional statements don’t have to include an else
. If there isn’t one, Python simply does nothing when the test is false:
num = 42
print 'before conditional...'
if num > 100:
print num, 'is greater than 100'
print '...after conditional'
before conditional...
...after conditional
We can also chain several tests together using elif
, which is short for “else if”. The following Python code uses elif
to print the sign of a number:
num = -3
if num > 0:
print num, "is positive"
elif num == 0:
print num, "is zero"
else:
print num, "is negative"
-3 is negative
One important thing to notice in the code above is that we use a double equals sign ==
to test for equality rather than a single equals sign. We do this because the single equals sign is used to assign values to variables.
We can also combine tests using and
and or
. and
is only true if both parts are true:
if (1 > 0) and (-1 > 0):
print 'both tests are true'
else:
print 'at least one test is false'
at least one test is false
while or
is true if at least one part is true:
if (1 > 0) or (-1 > 0):
print 'at least one test is true'
else:
print 'neither test is true'
at least one test is true
How many paths?
Which of the following would be printed if you were to run this code? Why did you pick this answer? Why not the other ones?
- A
- B
- C
- A and B
if 4 > 5:
print 'A'
elif 4 == 5:
print 'B'
elif 4 < 5:
print 'C'
How many paths, part 2
What would the answer be if we ran this code instead? Why?
- A
- B
- C
- A and B
if 5 => 5:
print 'A'
elif 5 == 5:
print 'B'
elif 5 < 5:
print 'C'
What is truth?
True
and False
are special words in Python called booleans
which represent true and false statements. However, they aren’t the only values in Python that are true and false. In fact, any value can be used as a test in an if
or elif
. After reading and running the code below, explain what the rule is for which values are considered true and which are considered false.
if True:
print 'True is true'
if False:
print 'False is false'
if '':
print 'empty string is true'
if 'word':
print 'word is true'
if []:
print 'empty list is true'
if [1, 2, 3]:
print 'non-empty list is true'
if 0:
print 'zero is true'
if 1:
print 'one is true'
Close enough
Write some conditions that print True
if the variable a
is within 10% of the variable b
and False
otherwise. Compare your implementation with your neighbor’s.
Combining loops and conditionals
Imagine that (for some strange reason) you want to write some code that:
- produces a list of 100 random integers between -10 and 10
- sums the positive and negative numbers in the list separately
Writing complex code is best done by working on individual parts. Let’s start by producing the list of random integers. Python has a library for producing random numbers called random
. One of the functions in this library is randint
, which produces random integers between some bounds:
import random
print random.randint(-10,10)
7
This command produces a single random number. We can run it repeatedly by writing a for
loop and building a list:
randomNumbers = [] # creates an empty list
for num in range(100):
randomNumbers.append(random.randint(-10,10))
print len(randomNumbers)
100
To finish our task, we write a for
loop that steps through the list of random integers and determines, using conditionals, if the values are positive or negative:
sumPositive = 0
sumNegative = 0
for num in randomNumbers:
if num > 0:
sumPositive = sumPositive + num
else:
sumNegative = sumNegative + num
print sumPositive, sumNegative
262 -290
Generalize your code
The code we wrote can be even shorter than it currently is! Rewrite the code with only one for loop and using in-place operators for the sums. Python (and most other languages in the C family) provides in-place operators that work like this:
x = 1 # original value
x += 1 # add one to x, assigning result back to x
x *= 3 # multiply x by 3
print(x)
6