有没有一种更简单的方法可以在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:不要重复自己。如果在多个地方使用相同的逻辑/功能,则应将其收集到一个地方。

除了提高可读性之外,这还有一个好处,那就是让你的生活变得更轻松。正如伟大的拉里·沃尔所说(我转述(;程序员的第一大美德是懒惰"假设您稍后想要对逻辑进行一些更改(例如,更改用户输入无效字符串时打印的消息(。使用DRY原理,您不必追踪代码中使用此循环的每一个部分(可能长达数千行(。相反,你去定义它的一个地方,并在那里做出改变。普雷斯托!

最新更新