我有一個小功能如下:
# Given the numerical value of a minute hand of a clock, return the number of degrees assuming a circular clock.
# Raise a ValueError for values less than zero or greater than 59.
def exercise_20(n):
try:
if n < 0 or n > 59:
raise ValueError("Number supplied is less than 0 or greater than 59")
except ValueError as ex:
print(ex)
else:
return n * 6
print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))
這是輸出:
Number supplied is less than 0 or greater than 59
None
180
Number supplied is less than 0 or greater than 59
None
為什么我在遇到例外時回傳“無”?
該函式正確列印適當值的例外,并為正確范圍內的值列印正確答案。
我不明白為什么它在遇到例外時也會列印“無”。
uj5u.com熱心網友回復:
你嘗試一個塊,如果它不符合你的條件if n < 0 or n > 59,你就加注。然后你抓住你的加薪并記錄下來。然后你什么都不回傳。捕獲和釋放是為了釣魚:)。
def exercise_20(n):
if n < 0 or n > 59:
raise ValueError("Number supplied is less than 0 or greater than 59")
return n * 6
print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))
您可能也對此感興趣:https ://softwareengineering.stackexchange.com/questions/187715/validation-of-the-input-parameter-in-caller-code-duplication# 。什么時候應該檢查輸入條件?呼叫者還是被呼叫者?
uj5u.com熱心網友回復:
你的函式應該只是引發錯誤。讓被稱為捕捉:
def exercise_20(n):
if n < 0 or n > 59:
raise ValueError("Number supplied is less than 0 or greater than 59")
return n * 6
for n in (-15, 30, 75, 30):
print(f"{n=}:", end=" ")
try:
print(exercise_20(n))
except ValueError as ex:
print(ex)
它將輸出:
n=-15: Number supplied is less than 0 or greater than 59
n=30: 180
n=75: Number supplied is less than 0 or greater than 59
n=30: 180
您的代碼回傳None是因為您return在print(ex). 因此 python 隱式回傳None.
uj5u.com熱心網友回復:
這是因為else:只有在沒有錯誤的情況下才會發生。因此,當出現錯誤時,它會跳過該else塊(也跳過它return內部),因此回傳None. 在函式定義中,您列印錯誤,在它之外,您列印回傳的內容,導致格式為
Error (if there is one)
Return value (None (if nothing is returned) or n*6)
檔案有更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476529.html
標籤:Python python-3.x
