Programming with Python

Repeating Actions with Loops

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.

Deep down, most people want to learn how to program so they can automate things. To do that, we’ll have to teach the computer how to repeat actions.

An example task that we might want to repeat is printing 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 items in a list that’s hundreds of values long, it would take a very, very long time.

It’s fragile: if we give it a longer list, it only prints part of the data, and if we give it a shorter one, it produces an error because we’re asking for characters 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 it 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 uses a for loop to repeat an operation once for each thing in a collection. The general form of a loop is:

for item in collection:
    do things with item

When writing a loop, 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 for); what is indented after the for statement belongs to the loop.

Here’s another loop that repeatedly updates a variable:

length = 0
word = 'elephant'
for letter in word:
    length = length + 1
print 'There are', length, 'letters in', word
There are 8 letters in elephant

It’s worth tracing the execution of this little program step by step. Since there are eight characters in ‘elephant’, the statement inside the loop will be executed eight times. The first time around, length is zero (the value assigned to it on line 1) and letter is “e”. The statement adds 1 to the old value of length, producing 1, and updates length to refer to that new value. The next time around, letter is “l” and length is 1, so length is updated to be 2. Once there are no characters left in “elephant” for Python to assign to letter, the loop finishes and the print statement 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 (with the last value it had inside the loop). We can re-use variables previously defined as loop variables, overwriting their value:

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 recognize 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 running different commands 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 commands in the indented block (i.e., the lines indented underneath it) are executed. If the test is false, the indented block beneath the else is executed instead. Only one or the other is ever executed.

Executing a Conditional
Conditional statements don’t have to include an else. If there isn’t one, Python simply does nothing if 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 between two values. The single equal sign is used for assignment.

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?

  1. A
  2. B
  3. C
  4. B and C
if 4 > 5:
    print('A')
elif 4 == 5:
    print('B')
elif 4 < 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 can be used in conditional statements. In fact, any value can be used 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 '':
    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 partner’s: do you get the same answer for all possible values of a and b?

Combining loops

Imagine that (for some strange reason) you want to write code that:

  • produces a list of 100 random integers between -10 and 10
  • sums the positive and negative numbers in the list separately

Let’s start by producing the list of random integers. Python has a library for producing random numbers, random, that we can use for this task. One of the functions in this library is randint, which produces random integers between some given 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

We can now write a for loop that steps through the list of random integers and determines 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

Our code could be even shorter than it currently is! Rewrite the script 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