gpt4 book ai didi

Python,无法将 input() 转换为 int()

转载 作者:行者123 更新时间:2023-11-28 21:49:22 24 4
gpt4 key购买 nike

我正在尝试使用以下代码将 input() 数据转换为 int():

prompt_text = "Enter a number: "
try:
user_num = int(input(prompt_text))
except ValueError:
print("Error")

for i in range(1,10):
print(i, " times ", user_num, " is ", i*user_num)

even = ((user_num % 2) == 0)

if even:
print(user_num, " is even")
else:
print(user_num, " is odd")

例如,当我输入 asd2 时,出现以下奇怪的错误:

Enter a number: asd2 Error 
Traceback (most recent call last): File "chapter3_ex1.py", line 8, in <module>
print(i, " times ", user_num, " is ", i*user_num)
NameError: name 'user_num' is not defined

我做错了什么?

最佳答案

您面临的问题是解释器在 try 中引发错误并执行 except block 。之后它将开始执行每一行。这将抛出 NameError

您可以通过将程序的其余部分放入 else block 来解决这个问题。

prompt_text = "Enter a number: "

try:
user_num = int(input(prompt_text))

except ValueError:
print("Error")

else:
for i in range(1,10):
print(i, " times ", user_num, " is ", i*user_num)

even = ((user_num % 2) == 0)

if even:
print(user_num, " is even")
else:
print(user_num, " is odd")

引自Python tutorial

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

另一种方法是使用哨兵值

prompt_text = "Enter a number: "
user_num = 0 # default value
try:
user_num = int(input(prompt_text))
except ValueError:
print("Error")

这也行得通。然而,结果可能不如预期。


提示 - 使用 4 个空格缩进

关于Python,无法将 input() 转换为 int(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586244/

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