Introduction to Python Programming

Chapter 5: Loops

Chapter 5 cover

Chapter outline

  • While loop
  • For loop
  • Nested loops
  • Break and continue
  • Loop else

Figure 5.1

  • credit: modification of work “Quantum Computing”, by Kevin Dooley/Flickr, CC BY 2.0
Quantum Computing illustration

5.1 While loop

  • Learning Objectives
  • Explain the loop construct in Python.
  • Use a while loop to implement repeating tasks.

While loop

  • Repeats a block while its condition remains True.
  • Condition is checked before each iteration.
  • Remember to update state to avoid infinite loops.

While loop (example video)

Counting with while loop


count = 1
while count <= 5:
    print(count)
    count += 1
Click the code above to simulate output...

Counting with while (video)

While loop — key takeaways

  • Use for unknown iteration counts; guard against infinite loops.
  • Update loop variables inside the body.

5.2 For loop

  • Learning Objectives
  • Explain the for loop construct.
  • Iterate over containers and sequences with for.
  • Use range() to generate sequences.

For loop overview

  • Iterates directly over items in an iterable (e.g., list, string, range).
  • Concise and avoids manual index bookkeeping.

for item in container:
    # process item
          

Iterating over a container


roster = ["Alice", "Bob", "Carol"]
for student in roster:
    print(student)
Click the code above to simulate output...

For loop with containers (video)

Using range()


for i in range(3):        # 0,1,2
    print(i)

for j in range(2, 5):     # 2,3,4
    print(j)

for k in range(1, 10, 3): # 1,4,7
    print(k)
          

For loop — key takeaways

  • Use for known iteration counts or container iteration.
  • range() supports start, stop, step.

5.3 Nested loops

  • Learning Objectives
  • Implement nested while loops.
  • Implement nested for loops.

Nested while loops


x = 1
while x <= 2:
    y = 1
    while y <= 3:
        print(x, y)
        y += 1
    x += 1
          

Nested while loops (video)

Nested for loops


courses = [["Alice", "Bob"], ["Carol", "Dan"]]
for course in courses:
    for student in course:
        print(student)
          

Nested for loops (video)

Nested loops — notes

  • Inner loops fully run for each outer-loop iteration.
  • Time complexity grows with product of loop sizes.

5.4 Break and continue

  • Learning Objectives
  • Analyze a loop’s control flow.
  • Use break and continue to control iteration.

break — exit loop early


while True:
    s = input("Enter 'q' to quit: ")
    if s == "q":
        break
    print("You entered:", s)
          

break (video)

continue — skip to next turn


for i in range(5):
    if i == 2:
        continue
    print(i)
          

continue (video)

Break & Continue — key points

  • break ends the loop immediately.
  • continue skips to the next iteration.

5.5 Loop else

  • Learning Objectives
  • Use a loop else clause to handle “no break” cases.
  • Apply with either for or while loops.

Loop else — behavior

  • else runs only if the loop **did not** encounter a break.
  • Useful for search patterns (“found” vs “not found”).

nums = [1, 2, 3, 4]
for n in nums:
    if n == 10:
        print("Found 10!")
        break
else:
    print("10 not found")
          

Loop else (video)

Finding the number 10 in a list

  • Demonstrates loop+break vs loop else “not found”.
compare loop+break vs loop else

Chapter 5 reference

  • Table 5.4 — Chapter 5 reference.
Reference Table

License

  • This ancillary resource is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 (CC BY NC-SA) license; it may be distributed, remixed, built upon for noncommercial purposes only, and must be attributed to OpenStax and redistributed under the same license.