Chapter 5

Loops and Repetition

Repetition is where a few lines of code start doing a great deal of work.

Chapter 5, Loops and Repetition

What you will learn

  • Use for loops with strings, lists, and range().
  • Use while loops for condition-controlled repetition.
  • Understand counters, accumulators, and sentinel values.
  • Avoid off-by-one errors and accidental infinite loops.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

5.1 for Loops

TPRM Lab 5.1: Iterate Through Text

Type this into a file, predict the output, then run it.

Python
word = "Python"

for ch in word:
    print(ch)

5.2 range() and Off-by-One Errors

TPRM Lab 5.2: Three Forms of range()

Type this into a file, predict the output, then run it.

Python
for i in range(5):
    print(i, end=" ")
print()

for i in range(2, 7):
    print(i, end=" ")
print()

for i in range(0, 20, 3):
    print(i, end=" ")

5.3 while Loops

TPRM Lab 5.3: A Small Menu Loop

Type this into a file, predict the output, then run it.

Python
choice = ""

while choice != "q":
    choice = input("Enter q to quit: ").lower()
    if choice != "q":
        print("Still running")

print("Goodbye")

Back to Python the TPRM Way