【问题标题】:How to use single try/block for multiple input function for integer validation in python?如何在 python 中使用单个 try/block 进行多个输入函数进行整数验证?
【发布时间】:2020-04-19 07:25:51
【问题描述】:

我是 python 新手,一直在尝试为抵押计算器编写一个小代码。我使用了三个变量,即利息、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

现在上面的代码对我来说很好,但我不乐意重复我的代码块。我希望使用函数或者可能是其他东西,所以必须尽量减少我的代码行。

有没有办法定义一个函数并在适当的验证下调用它?

提前致谢

【问题讨论】:

  • 是的,定义函数就是这样。你试过吗?发生了什么?
  • 是的,我试过这样做。我定义了一个函数,在函数中传入了变量。但是从那以后,我将 try 和 except 块放入函数和输入函数之外。它抛出和错误。 interest = int(input('Enter interest you want for the loan')) check_if_int_or_not(interest)
  • 这很奇怪吗?引发错误的代码需要在 try 块内
  • 我知道抛出错误的代码需要在 try/catch 块中。只是不知道如何使用函数将它放在那里。看起来可以简单地传递问题并将int(input(question)) 放在 try 块代码中。

标签: python validation input try-catch


【解决方案1】:

您可以定义一个为您处理验证过程的函数。
一个例子:

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:')

【讨论】:

  • 我们不必在return int(input(question)) 之后写break。既然是一个while循环,为什么输入正确的值后循环会自行停止?我们不需要明确写下break吗?
  • 如果转换为float时没有引发异常,则返回成功并将控制权交还给函数调用者
【解决方案2】:

您是绝对正确,将通用代码分解出来通常是一个好主意,因为这可以减少代码中的混乱,使其更加清晰和可维护。

例如,您可能希望在这里针对的情况是您的输入语句并不比以下内容更复杂:

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() 函数中,这样它就不会污染你的 main代码。举例来说,这是一个 minimalist 函数,可以满足您的需求:

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: ")

您可以从最后一行看到旧参数仍然可以正常工作,但是从前面两行中您知道可以指定允许的值范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多