[英]How to use single try/block for multiple input function for integer validation in python?
我是 python 的新手,一直在嘗試為抵押計算器編寫一個小代碼。 我使用三個變量,即利息、no_of_month 和 principal_amt,其值是使用輸入 function 獲取的。
下面是相同的代碼。
#######################
while True:
try:
no_of_month = int(input('Enter no of months you want for payment: '))
except ValueError:
print('The value you entered is not integer')
continue
else:
break
##############################
while True:
try:
interest = int(input('Enter interest you want for the loan: '))
except ValueError:
print('The value you entered is not integer')
continue
else:
break
################################
while True:
try:
principal_amt = int(input('Enter principal amount you want as loan:'))
except ValueError:
print('The value you entered is not integer')
continue
else:
break
現在上面的代碼對我來說很好,但我不樂意重復我的代碼塊。 我希望使用 function 或者可能是其他東西,所以必須盡量減少我的代碼行。
有沒有辦法定義 function 並通過適當的驗證調用它?
提前致謝
您可以定義一個 function 來為您處理驗證過程。
一個例子:
def get_input(question):
"""Read user input until it's not an integer and return it."""
while True:
try:
return int(input(question))
except ValueError:
print('The value you entered is not integer')
no_of_month = get_input('Enter no of months you want for payment: ')
interest = get_input('Enter interest you want for the loan: ')
principal_amt = get_input('Enter principal amount you want as loan:')
您絕對正確,將通用代碼分解出來通常是一個好主意,因為這可以減少代碼中的混亂,使其更加清晰和可維護。
例如,您可能希望在這里針對的情況是您的輸入語句並不比以下內容更復雜:
no_of_months = get_int("Enter no of months you want for payment: ")
interest = get_int("Enter interest you want for the loan: ")
principal_amount = get_int("Enter principal amount you want as loan: ")
然后將所有復雜的邏輯(打印提示、獲取值、檢查錯誤並在需要時重試)放在get_int()
function 中,這樣它就不會污染你的主代碼。 例如,這是一個極簡主義的 function 可以滿足您的要求:
def get_int(prompt):
while True:
try:
input_val = input(prompt)
return int(input_val)
except ValueError:
print(f"The value '{input_val}' is not a valid integer.\n")
當您想要添加額外的功能時,可以看到本地化代碼的優勢。 這通常可以通過使用默認參數無縫完成,但如果您決定使用它,仍然可以提供更多功能。
例如,考慮一種情況,您希望確保輸入的值在指定范圍內,例如,如果您決定貸款應該在一個月到三年(含)之間,或者利率必須大於 3%。 對get_int()
的一個簡單更改是:
def get_int(prompt, min_val = None, max_val = None):
while True:
# Get input, handle case where non-integer supplied.
try:
input_val = input(prompt)
value = int(input_val)
except ValueError:
print(f"The value '{input_val}' is not a valid integer.\n")
continue
# If min or max supplied, use that for extra checks.
if min_val is not None and min_val > value:
print(f"The value {value} is too low (< {min_val}).\n")
continue
if max_val is not None and max_val < value:
print(f"The value {value} is too high (> {max_val}).\n")
continue
# All checks passed, return the value.
return value
no_of_months = get_int("Enter no of months you want for payment: ", 1, 36)
interest = get_int("Enter interest you want for the loan: ", 3)
principal_amount = get_int("Enter principal amount you want as loan: ")
您可以從最后一行看到舊參數仍然可以正常工作,但是從前兩行中,您知道可以指定允許的值范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.