If/Else

Collatz Conjecture
Collatz Conjecture in Python
def steps(number):
    if number <= 0:
        raise ValueError("Only positive integers are allowed")
    counter = 0
    while number != 1:
        if number % 2 == 0:
            number /= 2
        else:
            number = number * 3 + 1
        counter += 1
    return counter

This approach starts with checking if the number is less than or equal to zero. If it is, then it raises a ValueError. After that, we declare a counter variable and set it to zero. Next, we start a while loop that will run until the number is equal to one, at which point it will terminate.

Inside the loop, we check if the number is even, and if it is, we divide it by two. If the number is odd, we multiply it by three and add one. After that, we increment the counter by one. When the loop completes, we return the counter value.

We use a while loop here because we don't know exactly how many times the loop will run — only that it will run until the number is equal to one.

12th Aug 2026 · Found it useful?