For Loops

CS 65: Introduction to Computer Science I

Looping through lists

So far, we've processed lists like this:

In [1]:
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

counter = 0
while counter < len(days_of_the_week):
    
    if "S" not in days_of_the_week[counter]:
        print(days_of_the_week[counter],"is a good day for programming")
        
    counter += 1
Monday is a good day for programming
Tuesday is a good day for programming
Wednesday is a good day for programming
Thursday is a good day for programming
Friday is a good day for programming

This pattern is so common there is a special loop for doing it without having to manage the counter yourself.

In [2]:
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]


for day in days_of_the_week:
    if "S" not in day:
        print(day,"is a good day for programming")
        
Monday is a good day for programming
Tuesday is a good day for programming
Wednesday is a good day for programming
Thursday is a good day for programming
Friday is a good day for programming

Notice: day became the value from the list for this iteration - we didn't have to do days_of_the_week[counter]

For loop syntax

  • keyword for
  • a loop variable - something new that you define here for the first time
    • it shouldn't be a variable you're already using for something else, this will change it!
  • keyword in
  • a sequence (like a list or a string)
  • a colon :
  • an indented block of code

Let's rewrite something like previous loops we've seen

In [3]:
with open("top_male_baby_names_2010s.txt") as male_names_file:
    
    male_names = male_names_file.readlines()
    
    total_length = 0
    
    counter = 0
    while counter < len(male_names):
        male_names[counter] = male_names[counter].rstrip()
        total_length += len(male_names[counter])
        counter += 1
        
    if counter != 0:
        average_length = total_length/counter
        print("Average length is",average_length)
Average length is 5.735
In [ ]:
#let's rewrite it here as a for loop
In [7]:
with open("top_male_baby_names_2010s.txt") as male_names_file:
    
    male_names = male_names_file.readlines()
    
    total_length = 0
    
    for name in male_names:
        
        name = name.rstrip()
        total_length += len(name)
        
    if len(male_names) > 0:
        average_length = total_length/len(male_names)
        print("Average length is",average_length)
Average length is 5.735

Group Exercises:

Write a for loop that will diplay all the temperatures in the list.

In [ ]:
 temperatures = [30, 20, 2, -5, -15, -8, -1, 0, 5, 35]

Once you have that working, change it so that it only displays the negative temperatures.