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 lessonThe 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: 8n = 6
steps = 0
# Print n, then apply Collatz rules until n reaches 1
# Count each transformation as a step
More While Loops exercises
- Countdown TimerBeginner
- Power of 2 FinderBeginner
- Predict the OutputBeginner
- Fix the Bug: Digit CounterBeginner
All Python exercises · 50 practice problems · Control Flow quiz