Automate the Boring Stuff - Collatz Exercise I wrote the following code for the Collatz exercise: The Collatz Sequence

Any feedback is appreciated.


  Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.


def collatz(n):
    while n &gt; 1:
        if n % 2 == 0:
            n = int(n // 2)
            print (n)
        elif n % 2 == 1:
            n = int(3 * n + 1)
            print (n)

n = int(input("Enter a number: "))
collatz (n)
A few simple observations:



    if n % 2 == 0:
        ...
    elif n % 2 == 1:
        ...



Here, we know that if n % 2 isn't 0, it must be 1, since n is an integer.  So that elif can be simply else, making it simpler to read.  More experienced programmers will reverse the test, knowing that 1 is the only truthy result of n % 2, so write if n % 2: ... ; else ....

    if ...:
        ...
        print (n)
    else:
        ...
        print (n)



The print that's present in both branches could be placed after the if/else, since it doesn't depend on the condition.
The results of the arithmetic expressions are already int, so no conversion is necessary.
The if/else could be reduced to a single line:

n = 3 * n + 1 if n % 2 else n // 2


but to me, that looks less clear, so I don't recommend that level of terseness here.




Modified code

Applying the observations above, I get a simpler version of the function:

def collatz(n):
    while n &gt; 1:
        if n % 2:
            n = 3 * n + 1
        else:
            n = n // 2
        print(n)