首页 > 解决方案 > 有没有更简单的方法来验证 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)))

标签: python

解决方案


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

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 的编程原则:不要重复自己。如果您在多个地方使用相同的逻辑/功能,则应该将其集中到一个地方。

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


推荐阅读