I wrote a program to do the collatz sequence in python 3. This was what I was asked to do:
Write a function named collatz()
that has one parameter named number. If
number is even, then collatz()
should print number // 2
and return this value.
If number is odd, then collatz()
should print and return 3 * number + 1
.
Then write a program that lets the user type in an integer and that keeps
calling collatz()
on that number until the function returns the value 1.
Remember to convert the return value from input()
to an integer with
the int()
function - otherwise, it will be a string value.
Here's my code:
def collatz(number):
while number is not 1:
if number % 2 == 0:
number = number // 2
print(number)
else:
number = 3 * number + 1
print(number)
p = int(input("Please input an integer: "))
print(p)
collatz(p)
I know I haven't added input validation, however apart from that could I get some feedback on this code? It works as intended.
I also saw this post and I don't get why they added the return statement after the print statement.