I'm trying to write a collatz program from the 'Automate the Boring Stuff with Python book', but have ran into some problems. I'm using python 3.5.2. Here's the project outline:
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.
My code:
def collatz(number):
if number % 2 == 0: #its even
print(number // 2)
return number // 2
elif number % 2 == 1: #its odd
print(3*number+1)
return 3*number+1
print('Type an integer: ')
num=int(input())
while(True):
if collatz(num) == 1:
break
# Or even simpler:
# while(collatz(num) != 1):
# pass
The output gives me an infinite loop:
Type an integer:
10
5
5
5
5
5
5
5
5
...
But when I break it down and use a variable to store the return value, it works:
while(True):
num=collatz(num)
if num == 1:
break
Output:
Type an integer:
5
16
8
4
2
1
Why is it? I don't understand why the first program doesn't work. Both are similar but I just chose to test the return value directly in my original program instead of using variables. I'd appreciate any help, Thanks.
num.