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
print(num)
elif num % 2 == 1:
num = 3 * int(num) + 1
print(num)
print(collatz(myInt))
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 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.
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