【发布时间】:2016-11-08 05:06:39
【问题描述】:
如何在此处引发异常以捕获非正输入?现在,如果我输入负数,则不会打印任何内容
"""
Generate fibonacci sequence to the nth digit
"""
def fib(n):
try:
if n <= 0:
raise Exception
prev = 0
curr = 1
for terms in range(0, int(n)):
nxt = prev + curr
print str(curr),
prev = curr
curr = nxt
except ValueError or Exception:
new = raw_input("Invalid input. Please enter a positive integer: ")
fib(new)
n = raw_input("Enter number of terms: ")
fib(n)
【问题讨论】:
-
您应该将负数测试移出
try- 您想要它会导致错误!另请注意,try块应尽可能短,except测试尽可能具体,否则会隐藏真正的问题。
标签: python exception numbers try-catch except