[英]“ during the handling of above exception, another exception occurred ” for the first input in the for loop
當我在 for 循環的輸入前面寫“int”時,我為非整數輸入寫的 try/except 塊回溯錯誤“在處理上述異常期間,發生了另一個異常”顯示。 但是,在該范圍內的所有其他輸入上,try/except 塊被識別並打印我寫的錯誤消息。
代碼
QLEN = 11
MAX_NUM = 12
for i in range(1,QLEN):
int2 = (random.randint(1,MAX_NUM))
int1 = (random.randint(1,MAX_NUM))
print()
print("Question {}".format(i))
try:
ans = int(input("{} + {}: ".format(int1,int2)))
add(int1,int2,ans)
except ValueError:
add(int1,int2,ans)
“添加” FUNCTION
def add(a,b,c):
if a + b != c:
print("Incorrect")
print("Correct Answer Was {}".format(a + b))
return (a + b)
print()
else:
print("Correct")
錯誤
Traceback (most recent call last):
File "main.py", line 125, in <module>
ans = int(input("{} + {}: ".format(int1,int2)))
ValueError: invalid literal for int() with base 10: 'e'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 128, in <module>
add(int1,int2,ans)
NameError: name 'ans' is not defined
您嘗試執行相同的欺詐代碼,導致在 except 塊中的 try 塊中出現異常。 此外 python 縮進約定是4 個空格,而不是兩個。 您的原始代碼將產生類似於此的錯誤消息:
Traceback (most recent call last):
File "/Users/eric/Desktop/ Python_Files/stackoverflow/0008.py", line 21, in <module>
ans = int(input("{} + {}: ".format(int1,int2)))
ValueError: invalid literal for int() with base 10: 'ans'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/eric/Desktop/ Python_Files/stackoverflow/0008.py", line 24, in <module>
add(int1,int2,ans)
NameError: name 'ans' is not defined
嘗試使用下面的代碼(除了塊不同)
import random
QLEN = 11
MAX_NUM = 12
def add(a,b,c):
if a + b != c:
print("Incorrect")
print("Correct Answer Was {}".format(a + b))
return (a + b)
print()
else:
print("Correct")
for i in range(1,QLEN):
int2 = (random.randint(1,MAX_NUM))
int1 = (random.randint(1,MAX_NUM))
print()
print("Question {}".format(i))
try:
ans = int(input("{} + {}: ".format(int1,int2)))
add(int1,int2,ans)
except ValueError:
print("You answered with something that wasn't an integer!")
用其他任何東西替換 except 塊,例如,在這種情況下,您沒有以正確格式回答的通知應該可以工作。
這是一個示例 output:
Question 1
9 + 10: 21
Incorrect
Correct Answer Was 19
Question 2
2 + 1: 3
Correct
Question 3
8 + 7: 15
Correct
Question 4
8 + 12: LOL
You answered with something that wasn't an integer!
int
因 ValueError 失敗,因為它無法解析不是 integer 的東西。 這導致它觸發了except
部分,該部分使用ans
調用add
。 但是, ans
是一個未知變量,因為它從未被賦值( int
failed ),在處理前一個時導致另一個異常。
與某些語言不同,在 Python 中,如果您不指定值,則不會有任何“默認”值。
這是更正后的片段:
print("Question {}".format(i))
try:
ans = int(input("{} + {}: ".format(int1,int2)))
except ValueError:
print("Bad input!")
continue
add(int1,int2,ans)
你期望失敗的是int
,所以你用try/except
包圍它。 如果失敗,您將continue
並因此跳過循環中稍后的add
調用。 如果沒有例外,那么你有一個很好的答案,你可以用所有ans
arguments 調用add
。
此外,在return (a+b)
之后的print()
永遠無法執行,因為return
將離開 function。 此外,您不需要在諸如int2 = (random.randint(1,MAX_NUM))
類的表達式中使用外括號,因為它們只會增加混亂,並且可能會與具有一個元素的元組混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.