Skip to main content

While and For Loops

Repeating Code in Python

· 3 min read

In the previous unit, we covered pattern matching with match-case. Now let's look at loops, which let you repeat code without writing it multiple times.

While and For Loops

while Loops

A while loop runs as long as its condition is true. Use it when you don't know ahead of time how many iterations you need.

count = 0
while count < 5:
print(count)
count += 1

This prints 0 through 4. The loop checks count < 5 before each iteration. Once count hits 5, the condition is false and the loop stops.

The += operator is shorthand for count = count + 1. You'll see this pattern constantly in loops.

for Loops

A for loop iterates over a sequence like a list, string, or range. Use it when you know what you're iterating over.

for i in range(5):
print(i)

This also prints 0 through 4. The range(5) function creates a sequence of numbers from 0 to 4. Each iteration, the loop assigns the next value to i and runs the body.

The variable name i is convention for counting loops, but you can use any name. For clarity, use descriptive names when iterating over meaningful data: for student in students is clearer than for x in students.

break and continue

Two keywords give you finer control over loops.

break exits the loop entirely.

for i in range(10):
if i == 5:
break
print(i)

This prints 0 through 4. When i equals 5, break stops the loop.

continue skips the rest of the current iteration and moves to the next.

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

This prints 0 through 9, except 5. When i equals 5, continue skips the print and moves to the next iteration.

Project: Draw a Pattern of Shapes

Let's combine both loop types with Turtle. This program uses a for loop to draw multiple shapes and a while loop to draw each individual shape.

import turtle

screen = turtle.Screen()
screen.bgcolor("white")

t = turtle.Turtle()

num_sides = 5
angle = 360 / num_sides
distance = 100

for _ in range(num_sides):
count = 0
while count < num_sides:
t.forward(distance)
t.right(angle)
count += 1
t.right(angle)

turtle.done()

The outer for loop runs 5 times. Each iteration, the inner while loop draws a pentagon, then the turtle rotates to position for the next shape. The result is 5 pentagons arranged in a star pattern.

Try changing num_sides to see how different values affect the pattern. Squares with num_sides = 4 create a different arrangement than hexagons with num_sides = 6.

In the next unit, we'll look at functions and how to define reusable blocks of code.