Python Forum

Full Version: Function and return value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def COLLATZ(NUM):
    if NUM == 1:
        return NUM
    elif (NUM%2 == 0):
        NUM = NUM/2
        print(NUM)
        COLLATZ(NUM)
    else:
        (NUM%3) == 1
        NUM = (NUM*3)+1
        print(NUM)
        COLLATZ(NUM)

print("Enter Number")
N = int(input())
NN = COLLATZ(N)
print("Enter the last Value", NN)
1. In the last iteration NUM becomes 1 and it should return NUM. Apparently it is returning None. Can someone please explain the logic behind None ?
if initial value of NUM is !=1 it will enter elif or else part of the if block. there it will run recursively until NUM == 1 and then will finish initial call to COLLATZ, effectively returning None

What you should do
def COLLATZ(NUM):

    if NUM == 1:
        return NUM
    else:
        if (NUM%2 == 0):
            NUM = NUM/2
        else:
            NUM = (NUM*3)+1
        print(NUM)
        return COLLATZ(NUM)
 
print("Enter Number")
N = int(input())
NN = COLLATZ(N)
print("Enter the last Value", NN)
And please, don't use ALLCAPS for variable and function names. Per convention ALLCAPS is used for constants