Why doesn't the loop end the first time collatz()
returns 1?
def collatz():
global number
if number % 2 == 0:
number = number // 2
print(number)
return number
else:
number = 3 * number + 1
print(number)
return number
try:
number = int(input('Please enter an integer except zero.\n'))
except ValueError:
print("ValueError: invalid value.")
number = int(input('You must enter an integer except zero.\n'))
while collatz() != 1: # if input(4), the output will be: 4 2 1 4 2 1
collatz()
# another way, which works:
while number != 1: --> # also input(4), the output will be: 4 2 1
collatz()
In your first method, you call
collatz()
twice in each loop:while collatz() != 1:
, where the return value gets tested. If it returns 1 at this point, you will exit the loop.while
line.So, when you input 4, your output is:
You could also write your loop like:
A bit of advice:
collatz()
function take a number as parameter, and return the next value. Leave the printing to the rest of the code.You could modify it like this, for example: