我是python的新手,一直在尝试为抵押贷款计算器编写一个小代码。我使用了三个变量,即interest、no_of_month和principal_amt,其值使用输入函数获取。
以下是相同的代码。
#######################
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
现在上面的代码对我来说很好,但我不喜欢重复我的代码块。我希望使用函数,或者可能是其他东西,所以必须尽量减少我的代码行。
有没有一种方法可以定义一个函数并在适当的验证下调用它?
提前感谢
您可以定义一个函数来负责验证过程
一个例子:
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()
函数中,这样它就不会污染主代码。举个例子,这里有一个极简主义函数,它可以做你想要的:
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: ")
从最后一行中可以看出,旧参数仍然可以正常工作,但从前两行中,您知道可以指定允许的值范围。