我创建了一个程序,用户输入一个数字,程序将计算到该数字,并显示它花了多少时间。但是,每当我输入字母或小数(即0.5)时,我都会收到错误。以下是完整的错误消息:
Traceback (most recent call last):
File "C:\Documents and Settings\Username\Desktop\test6.py", line 5, in <module>
z = int(z)
ValueError: invalid literal for int() with base 10: 'df'
我该怎么做才能解决这个问题?
以下是完整代码:
import time
x = 0
print("This program will count up to a number you choose.")
z = input("Enter a number.\n")
z = int(z)
start_time = time.time()
while x < z:
x = x + 1
print(x)
end_time = time.time()
diff = end_time - start_time
print("That took",(diff),"seconds.")
请帮忙!
答案 0 :(得分:8)
嗯,确实有一种'修复'的方法,它表现得像预期的那样 - 你不能写一个字母到int,这没有多大意义。你最好的选择(这是一种pythonic的做事方式),就是简单地用try来编写一个函数......除了块:
def get_user_number():
i = input("Enter a number.\n")
try:
# This will return the equivalent of calling 'int' directly, but it
# will also allow for floats.
return int(float(i))
except:
#Tell the user that something went wrong
print("I didn't recognize {0} as a number".format(i))
#recursion until you get a real number
return get_user_number()
然后你会替换这些行:
z = input("Enter a number.\n")
z = int(z)
与
z = get_user_number()
答案 1 :(得分:1)
尝试检查
if string.isdigit(z):
然后执行其余的代码,如果它是一个数字。
因为你以1为间隔计算,所以保持int()应该是好的,因为你不需要小数。
编辑:如果您想要捕获异常而不是下面的wooble建议,那么这是代码:
try:
int(z)
do something
except ValueError:
do something else