Python,无法将input()转换为int() [英] Python, unable to convert input() to int()
问题描述
我正在尝试使用以下代码将input()数据转换为int():
I am trying to convert input() data to int() with the following code:
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 时,出现以下奇怪错误:
I get the following odd error when I enter asd2 for example:
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
块.之后,它将开始执行everyline.这将抛出NameError
The problem that you are facing is that the interpreter raises the error in the try
and executes the except
block. After that it will start to execute everyline. This will throw the NameError
您可以通过将程序的其余部分放入else
块中来克服这一问题.
You can overcome that by putting the rest of the program into the 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教程
try ... except语句具有 可选else子句 , 当前,必须遵循所有除条款.对于以下代码很有用 如果try子句未引发异常,则必须执行 .
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.
另一种方法是使用 sentinel 值
prompt_text = "Enter a number: "
user_num = 0 # default value
try:
user_num = int(input(prompt_text))
except ValueError:
print("Error")
这也将起作用.但是结果可能与预期不符.
This will also work. However the results may not be as expected.
Protip-使用4个空格缩进
Protip - Use 4 spaces to indent
这篇关于Python,无法将input()转换为int()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!