Home CPSC 110

Looping Continued

For Loops

There is another type of loop in Python called a "for" loop. A for loop is different in that it loops through every element in a sequence. A for loop has the following form:

for item in sequence:
    line 1
    line 2

With a for loop, the item takes on the value of each thing in the sequence, one by one.

The only type of sequence we have seen so far is a string which is a sequence of characters. The following for loop cycles through every character in the string:

name = "Bob Smith"
for char in name:

A for loop can always be replaced by an equivalent while loop, but a for loop has a few benefits when looping through a sequence:

The range Function

The range function is used to create a sequence of numbers. This function allows us to write for loops using sequences of numbers.

If we pass range 1 number, it will give us a sequence from 0 up to (but not including) that number. For example:

for i in range(10):

This will print the numbers 0 through 9. In this way, we can write loops that execute a fixed number of times. For example, if we want to print "Hi" 5 times, this is all we need to do:

for i in range(5):

If we don't want to start on 0, we can also pass range a starting point. If we give it 2 numbers, the first is the start and the second is 1 past the ending point:

for i in range(5, 11):

This program will print the numbers from 5 to 10.

Lastly, we can pass three numbers into range. Then it will treat the last one as the step between each. For example, if we want to go through even numbers only, we could pass a step of 2:

for i in range(2, 11, 2):

We could also pass a negative number to go backwards:

for i in range(10, 0, -1):

Example: Temperature Table

How could we write a program which prints a table showing the conversion between Celsius and Fahrenheit? The program should print the equivalent temperatures for starting at 0° through 100° Fahrenheit, in increments of 5°.

To convert Fahrenheit to Celsius, subtract 32 and then multiply by $\frac{5}{9}$.

for far in range(0, 101, 5):
    cel = (far - 32) * 5/9
    cel = round(cel, 2)
    print(far, "degrees F =", cel, "degrees C")

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.