0
votes

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)
2
The print statement is unreachable - when do you anticipate your program reaching it? - miradulo
BTW, since you are dealing with integers you should be using the // floor division operator instead of /, which always returns a float in Python 3. - PM 2Ring
Unless you are doing this as an exercise in recursion, a recursive Collatz is probably a bad idea. You will blow the stack with (some) larger numbers. - John Coleman

2 Answers

3
votes

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.

1
votes

As others have mentioned, all of the execution paths in your function end in a return statement, so that print call is unreachable. So if you want each value of n or i to be printed you need to move the call to somewhere that it will be reachable. ;)

Also, there's a little bit of redundancy in that code. You don't need

i.append(n)
return collatz(n)

in both the if and else branches, you can move them outside the if...else block.

Here's a modified version of your code. I've also changed the / operators to // so that the results of the divisions will be integers.

i = []

def collatz(n):
    print(n)
    if n==1:
        return i
    if n%2 == 0:
        n = n // 2
    else:
        n = ((n*3) + 1) // 2
    i.append(n)
    return collatz(n)

# Test

print(collatz(12))

output

12
6
3
5
8
4
2
1
[6, 3, 5, 8, 4, 2, 1]