gpt4 book ai didi

python - 值错误 : invalid literal for int() with base 10 -- how to guard against invalid user input?

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:15 25 4
gpt4 key购买 nike

我制作了一个程序,用户可以在其中输入一个数字,该程序会计算到该数字并显示花费了多少时间。但是,每当我输入字母或小数(即 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.")

请帮忙!

最佳答案

好吧,确实有一种方法可以“解决”这个问题,它的行为符合预期——您不能将字母大小写转换为 int,这实际上没有意义。你最好的选择(这是一种 pythonic 的做事方式)是简单地编写一个带有 try...except block 的函数:

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 ValueError:
#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()

关于python - 值错误 : invalid literal for int() with base 10 -- how to guard against invalid user input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6393635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com