def collatz(number):
while number != 1:
if number % 2 == 0:
print(number)
number=number//2
elif number %2 ==1:
print(number)
number=number*3+1
else:print(number)
print('Enter number')
while True:
try:
number=int(input())
collatz(number)
except ValueError:
print('请输入一个整数')
——————————————————
我暂时没想到怎么结束主程序的循环,就是最后返回1之后光标还闪着,会要求继续输入数字
————————————————
想到怎么结束了,不过码起来好像很臃肿,初学者,求指导
修改后的答案:
def collatz(number):
while number != 1:
if number % 2 == 0:
print(number)
number=number//2
elif number %2 ==1:
print(number)
number=number*3+1
else:print(number)
print('Enter number')
while True:
try:
number=int(input())
collatz(number)
break
except ValueError:
print('请输入一个整数')