我在捕獲 ValueError 例外時遇到了一些麻煩。
- 如果我使用字串(即“a”)而不是提供 int 數字來測驗輸入,那么它會按預期拋出 ValueError。但是為什么我的例外沒有捕捉到這個并列印“錯誤,用整數再試一次”?
我給了它've',因為我還沒有使用這個變數。我沒有給出'e',因為我已經將它用于另一個例外。
- 如果我改為嘗試 except (TypeError,ValueError): 那么為什么這也不起作用?
注意,這段代碼只是為了我練習處理例外,內容本身沒有意義。
while not correct_input:
distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
monetary_value = float(input("amount paid to cover distance: "))
price_per_litre = 1.59
try:
fuel_consumed = monetary_value/price_per_litre
if monetary_value/price_per_litre < 0:
raise Exception #I can raise my own custom exception here
except Exception as e:
print("too small, try again")
except ValueError as ve: #Catch our exception, and handle it properly. Ensure specific exceptions at the top, general at the bottom
print("error, try again with an integer")
else: #Runs code if try doesn't raise an exception
print(fuel_consumed)
correct_input = True
finally: #Regardless of error or not, what you wish for it to do. i.e. close a file, close database etc
continue
謝謝
uj5u.com熱心網友回復:
< 0只有當你輸入負值時你才會滿足這個條件,請看你想要還是想要< 1。否則代碼如下。
correct_input = False
while not correct_input:
try: # just check if you are getting integer/floating value here only
distance_travelled = float(input("enter distance travelled in km: ")) #input enters strings, so you must convert to the datatype you want
monetary_value = float(input("amount paid to cover distance: "))
except:
print('Only Integer and Floting point number')
price_per_litre = 1.59
try:
fuel_consumed = monetary_value/price_per_litre
if monetary_value/price_per_litre < 0: # I have a doubt if you really want 0 here. OR 1
raise ValueError # raise value error when condition is met.
except ValueError as ve:
print('Too Small')
else:
print(fuel_consumed)
correct_input = True
finally:
continue
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426246.html
