Book a free demo

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

  1. 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.
  2. Starting at 27 takes 111 steps and climbs as high as 9,232 before falling back to 1.
  3. The program counts the steps and remembers the highest value. Try other starting numbers.
See the Python path โ†’

Try this

  • 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.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All 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

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

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.

All free games โ†’
Chat on WhatsApp
Esc

Try