Editor

The Collatz Sequence

Beginner · Write the code · from Python While Loops: When For Loops Aren't Enough

From the lesson: Python While Loops: When For Loops Aren't Enough

A vending machine doesn't know how many coins you'll insert. It just keeps waiting: "while the total is less than the price, keep accepting coins." It can't use a for loop because it doesn't know the number of iterations in advance. It needs a while loop.

Read the lesson

The Collatz conjecture is a famous math problem. Start with any positive integer. If it's even, divide by 2. If it's odd, multiply by 3 and add 1. Repeat until you reach 1.

Starting with n = 6, print each value in the sequence (including 6 and 1), then print how many steps it took.

Expected output:

6
3
10
5
16
8
4
2
1
Steps: 8
n = 6
steps = 0
# Print n, then apply Collatz rules until n reaches 1
# Count each transformation as a step

More While Loops exercises

All Python exercises · 50 practice problems · Control Flow quiz