我正在尝试编写一个Collatz序列,同时添加一个try和except语句来检测用户是否输入非整数字符串,而我似乎无法弄清楚如何这样做。如果阅读Try/Except in Python: How do you properly ignore Exceptions?,但仍然感到茫然。到目前为止我的代码:
def collatz(y):
try:
if y % 2 == 0:
print(int(y/2))
return int(y/2)
else:
print(int(y*3+1))
return int(y*3 +1)
except ValueError:
print('Error: Invalid Value, the program should take in integers.')
print('Please enter a number and the Collatz sequence will be printed')
x = int(input())
while x != 1:
x = collatz(x)
答案 0 :(得分:2)
在非整数输入上,程序将在您编写代码时使用代码调用collatz()
之前失败,这意味着您的try
块不会捕获异常:
def collatz(y):
try:
if y % 2 == 0:
print(int(y/2))
return int(y/2)
else:
print(int(y*3+1))
return int(y*3 +1)
except ValueError:
print('Error: Invalid Value, the program should take in integers.')
print('Please enter a number and the Collatz sequence will be printed')
x = int(input()) # <-- THIS throws ValueError if input is non integer...
while x != 1:
x = collatz(x) # <-- ...but your try/except is in here.
而是将输入转换包装在同一个try / except中。然后在collatz()
函数中没有必要:
def collatz(y):
if y % 2 == 0:
print(int(y/2))
return int(y/2)
else:
print(int(y*3+1))
return int(y*3 +1)
print('Please enter a number and the Collatz sequence will be printed')
try:
x = int(input())
except ValueError:
print('Error: Invalid Value, the program should take in integers.')
exit()
while x != 1:
x = collatz(x)