Why doesn\'t the loop end the first time collatz()
returns 1?
def collatz():
global number
if number % 2 == 0:
number = number // 2
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:
while collatz() != 1:
pass # do nothing
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:
def collatz(n):
if n % 2 == 0:
n = n // 2
else:
n = 3 * number + 1
return n
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 True: # infinite loop
number = collatz(number)
print(number)
if number == 1:
# we break out of the loop
break