【发布时间】:2019-09-06 14:38:06
【问题描述】:
我是编程新手,我试图了解 Python 如何解释命令,在这种情况下,我无法理解 Python 如何知道使用 try-except 子句识别整数、浮点数或字符串。这是我的代码(请原谅厚脸皮)
print("DETECTING INPUT TYPE WITH LIMITED CHANCES")
print("Enter an integer and ONLY AN INTEGER. YOU HAVE ONLY 5 CHANCES")
n=0
final=0
for n in range(5):
abc=input()
try:
int(abc) #This line checks for whether the input is an integer. If this is a floating number, the int() operator executes and
# converts the number to an integer
final=1
break
except:
try:
float(abc)
print("WHAT DID I TELL YOU? YOU PUT IN A FLOATING NUMBER! DO IT RIGHT!")
print("Enter an integer and ONLY AN INTEGER")
except:
print("...you put a string didn't you? HOW DARE YOU DEFY THIS PROGRAM? DO IT RIGHT!")
print("Enter an integer and ONLY AN INTEGER")
if final==1:
print("Good... very good, here is your number:",abc)
else:
print("You were given 5 chances and you couldn't get it right.")
此代码按预期工作,但是当我放入一个浮点数时,程序如何抛出异常以允许 try-except 子句执行?例如,当我在执行程序时输入“1.0”时会发生以下情况:
DETECTING INPUT TYPE WITH LIMITED CHANCES
Enter an integer and ONLY AN INTEGER. YOU HAVE ONLY 5 CHANCES
1.0
WHAT DID I TELL YOU? YOU PUT IN A FLOATING NUMBER! DO IT RIGHT!
Enter an integer and ONLY AN INTEGER
然后我纠正自己并输入一个整数时的样子:
1
Good... very good, here is your number: 1
但是,如果我在控制台中手动输入以下内容,我不会收到错误消息。相反,int() 命令执行它应该做的事情,并将我的浮点数转换为整数。
abc=1.0
int(abc)
Out[3]: 1
try-except 子句对 int() 运算符做了什么以引发异常并允许我的代码正确执行?
谢谢!
【问题讨论】:
-
我认为问题在于 input() 函数总是返回一个字符串,所以错误来自
int("1.0")。这就是为什么使用 try/except 而不指定您期望的错误类型通常是不好的做法。 -
知道了,我会在以后使用 try/except 子句时记住这一点
标签: python