pythonmathcollatz

Collatz Conjecture in Python


I'm relatively new to Python and I decided to try and code a relatively simple collatz conjecture where the user enters a number (integer). The code is just a simple function that calls itself. i is a list that should have every number that the function calculates appended to it. I'm new to executing Python scripts and I have tried using the IDLE shell to run the code. It asks me what number I want but when I enter a number nothing is printed? I'm sure I just need to edit a small bit of this code (or maybe it's all wrong yikes) but does anybody have any idea why my script returns nothing? Sorry about this and thanks. Here's the code:

l = input("Enter a number: ")
l = int(l)
i = []
def collatz(n):
    if n==1:
        return i
    if n%2 == 0:
        n = n/2
        i.append(n)
        return collatz(n)
    else:
        n = ((n*3) + 1) / 2
        i.append(n)
        return collatz(n)
    print(i)
collatz(l)

Solution

  • There are three returns before your print and one of them is inside an else statement, which means that at least one of them will be executed, so your print won't even be reached to be executed, you should move it right after the function definition to see something:

    def collatz(n):
        print(i) # <= print here
        if n==1:
            ....
    

    See more about the return statement. A snippet:

    return leaves the current function call with the expression list (or None) as return value.