有没有更简单的方法来验证python中的用户输入而不重复while循环?

我目前正在学习 python,我想知道是否有更简单的方法来验证用户输入。我正在研究身体质量指数计算器。即使代码正常工作,我觉得这不是最佳实践,并且有一种更简单的方法来验证用户输入而不使用多个 while 循环。

现在我的代码如下所示。

print("#########################################################n"
      "############## Body Mass Index calculator ###############n"
      "#########################################################n")


# asks user to input his height
height = input("Please enter your height in m: ")

# mechanism to check if the user input is valid input
while True:

    # checks if the user input is a float
    try:
        float(height)
        new_height = float(height)
        break

    # if the user input is not a float or a number, it prompts the user again for valid input
    except ValueError:
        print("Enter a valid height...")
        height = input("enter your height in m: ")
        print("")
        continue

weight = input("Please enter your weight in kg: ")

while True:
    # checks if the user input is a float
    try:
        float(weight)
        new_weight = float(weight)
        break

    # if the user input is not a float or a number, it prompts the user again for valid input
    except ValueError:
        print("Enter a valid weight...")
        weight = input("enter your weight in kg:")
        print("")
        continue

# calculating the body mass index
body_mass_index = new_weight / new_height**2

# printing out the result to the user
print("nYour BMI is " + str(round(body_mass_index, 2)))

回答

像这样重复的代码最好放在一个函数中。这是一个例子。

def get_float_input(var, units):
    while True:
        value = input('enter your {} in {}: '.format(var, units))
        try:
            return float(value)
        except ValueError:
            print('Invalid entry!')

height = get_float_input('height', 'm')
weight = get_float_input('weight', 'kg')

有一个称为 DRY 的编程原则:不要重复自己。如果您在多个地方使用相同的逻辑/功能,则应将其集中到一个地方。

除了提高可读性外,这还有利于让您的生活更轻松。正如伟大的拉里·沃尔 (Larry Wall) 所说(我是这样解释的),“程序员的第一大美德是懒惰。” 假设您稍后想对逻辑进行一些更改(例如,更改用户输入无效字符串时打印的消息)。使用 DRY 原则,您不必追踪使用此循环的代码中的每个部分(可能长达数千行)。相反,您转到定义它的一个地方并在那里进行更改。快!


以上是有没有更简单的方法来验证python中的用户输入而不重复while循环?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>