我是编程新手,我试图理解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
的结果是一个字符串。要在控制台中复制它,您应该这样做
abc = "1.0"
然后int(abc)
将按预期引发一个 ValueError。