Easy ยท ages 11+ ยท while loop ยท if / else ยท maths puzzle
The Collatz sequence in Python.
Start with any number. If it is even, halve it; if odd, triple it and add 1. See how long it takes to reach 1.
The program
Press Run to see what it prints. Change anything you like, then run it again.
n = 27
steps = 0
highest = n
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps = steps + 1
if n > highest:
highest = n
print("Steps:", steps)
print("Highest number reached:", highest)Steps: 111 Highest number reached: 9232
How it works
- The Collatz conjecture says that this process always ends at 1, whichever number you start with. Nobody has proved it, even though computers have checked huge numbers.
- Starting at 27 takes 111 steps and climbs as high as 9,232 before falling back to 1.
- The program counts the steps and remembers the highest value. Try other starting numbers.
Try this
- Try a starting number from 1 to 30 and see which takes the longest.
- Print the whole sequence.
- Use a
forloop to find the starting number below 100 with the most steps.
Stuck on an error? Read how to debug Python.
Similar ideas
More programs
FAQ
The Collatz sequence: questions
What does the the collatz sequence program do?
Start with any number. If it is even, halve it; if odd, triple it and add 1. See how long it takes to reach 1. It prints: Steps: 111 / Highest number reached: 9232
Which Python ideas does it use?
while loop, if / else, maths puzzle. Easy level, suitable from about age 11.
How do I run it?
Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.
What should I try next?
Try a starting number from 1 to 30 and see which takes the longest. Print the whole sequence. Use a for loop to find the starting number below 100 with the most steps.
Start a conversation
Want a teacher to guide the learning?
Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.
- Tell us the learnerโs age or grade and goals
- Weโll suggest a suitable class or learning path
- Weโll confirm format, timing and fees with a parent or guardian
Play it, don't just read it
Write some code right now
Free games that need no sign-up. Pick one and play for five minutes.
Pick a game
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay