Why do I get a NoneType object?

Hi campers,

In parallel to the Python Computing course, I’m doing some projects from the Automate the Boring Stuff with Python book.

One of them, the “kollatz sequence” asks to write a sequence that will eventually arrive at number 1. In my case, the program always ends with a NoneType after 1. I’m trying to understand where this is coming from.
Many thanks for your help!

print("This is the collatz sequence")
myInt = int(input("Enter a number: "))

def collatz(num):
    while num != 1:    
        if num % 2 == 0:
            num = int(num) // 2
        elif num % 2 == 1:
            num = 3 * int(num) + 1

I think you first need to change the input string to number, i.e., num = int(num), before the while loop condition check.

Hi @Anapi. I believe it is because you are not returning a value from collatz but you are still printing its return value. Try collatz(myInt).

Hi @Anapi

Short Answer: instead of using print(num) use return num…

You use print statement inside the function, so when you call the function it execute the code & when it see print, python thinks (“Ok there is print statement, let’s print in here”) when it comes outside the function, python again see the print statement but python doesn’t return anything (“That means it doesn’t have anything to print”) then shows None

Print() is a inbuilt python function also I mention here as a statement… Because if the answer get so much print words readers get confuse.

Thanks, it worked like a charm!

1 Like

Thanks for the answer! The code worked by removing the print statement from the last line.

1 Like

Thanks for the explanation, I’m still mixing up the print and return functions.
When I used return, it gave me an error that “return” is outside the function, but just removing it did the job.

1 Like

Sorry for late reply, Check out the intentation after the semicolon, return statement must inside the certain while statement not inside the f or else. . I think so