为什么第一次collatz()
返回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()
答案 0 :(得分:1)
在第一种方法中,您在每个循环中调用collatz()
两次:
while collatz() != 1:
,其中测试返回值。如果此时返回1,则退出循环。while
行。因此,当您输入4时,输出为:
你也可以写下你的循环:
while collatz() != 1:
pass # do nothing
一些建议:
collatz()
函数将数字作为参数,并返回下一个值。将打印保留到代码的其余部分。您可以像这样修改它,例如:
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