Skip to content

Sep 28: for Statements and Lists

Meet in King 248

Learning Objectives

After today's class, you should be able to:

  • Explain the syntax and meaning of a for statement.
  • Predict how many times a loop runs and what it produces.
  • Write for loops that iterate over lists and strings.

Lesson Outline

Presentation [10 min]

  • Introduction to for loops, lists, and ranges

Reading Loops [20 min]

For each loop below, predict:

  • How many times does the loop run?
  • What is the output printed on the screen?
  • What is the final value of the loop variable?

Writing Loops [20 min]

  • Solve at least 3 problems on CodingBat

Your To-Do List

  • Read the Week 6 guide and begin studying

Example Loops

Run each example in Python Tutor to check your answers!

Example 1: for each element of a list

words = ["Pause", "brink", "fox", "Cup", "match", "sound",
            "president", "Restless", "despise", "Rack"]
for word in words:
    if word[0].isupper():
        print(word, "is capitalized")

Example 2: for each character in a string

message = "Please help!"
for c in message:
    if c not in ['a', 'e', 'i', 'o', 'u']:
        print(c, end="")
print()

Example 3: for each integer in a range

print("1 bottle of pop")
for number in range(2, 7):
    print(number, "bottles of pop")
print("7, 7, bottles of pop!")

CodingBat Loops

CodingBat.com is a free site of live problems to build skill in Java and/or Python. CodingBat was created by Nick Parlante, who is Computer Science lecturer at Stanford.

Note: Do not use the built-in min(), max(), or sum() functions for any of these problems.

List-2 Problems

  • Easier: count_evens, has22
  • Medium: big_diff, sum13
  • Harder: centered_average, sum67

String-2 Problems

  • Easier: double_char, count_hi
  • Medium: count_code, cat_dog
  • Harder: xyz_there, end_other