[英]How to fix "During handling of the above exception, another exception occurred: "
每當我輸入的數據不止一次導致程序崩潰時,我該如何解決這個錯誤。 這是我的代碼及其輸出的內容,它應該不斷重復,直到輸入正確的數據。
flag=False
while flag==False:
try:
number=int(input("Enter number of books: "))
except ValueError:
print("Please enter number of books as a positive whole number ")
number=int(input("Enter number of books: "))
else:
flag=True
Traceback (most recent call last):
File "C:\Users\Alex\OneDrive\Documents\ComputerScience\Intro2.py", line 5, in <module>
number=int(input("Enter number of books: "))
ValueError: invalid literal for int() with base 10: '3.3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Alex\OneDrive\Documents\ComputerScience\Intro2.py", line 8, in <module>
number=int(input("Enter number of books: "))
ValueError: int() 以 10 為底的無效文字:'3.4'
試試這個,它會評估你的字符串是否是數字,然后打破外觀。 異常處理在計算方面是昂貴的,應盡可能避免
while True:
no_of_books = input("enter number of books")
if no_of_books.isdigit():
break
您的代碼沒有不斷重復的原因是它在第 5 行出現異常,該異常被包裝在 try 塊中,然后在 except 塊中它在第 8 行引發了另一個異常,該異常沒有被包裝在 try 塊中,因此它終止了
更新以響應評論,只需將您的字符串轉換為這樣的 int 然后使用int_number_of_books
作為 int
while True:
no_of_books = input("enter number of books")
if no_of_books.isdigit():
int_number_of_books = int(no_of_books)
break
if int_number_of_books <= 0:
# your code here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.