I have recently started studying Python and the book tasked me with creating a function that would write the Collatz sequence starting with an input number but, despite the while
loop, it will only run once if i use the return
statement. Why is that? The program runs correctly if i
change it into n =
, but what's the point of return
then?
Here's the current code:
def collatz(n):
while n!=1:
print(n)
if n%2==0:
return n//2
else:
return n*3+1
print('Insert a number.')
while True:
try:
print(collatz(int(input())))
except ValueError:
print('Please insert an integer number.')
If i were to type 33, it will only print:
>>>>33
>>>>100
and then stop. Thus returning the new value only once.