python - 有没有更简单的方法来验证 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 原则,您不必跟踪代码中使用此循环的每个部分(可能长达数千行)。相反,您转到定义它的一个地方并在那里进行更改。快!
推荐阅读
- python - 如何在python中连接两个数组?
- java - 使用 axios 将字符串数组传递给 Java REST API 不起作用
- wordpress - woocomerce - 在类别中显示产品
- android - AsyncTask -> Error :Thread ...: reacting to signal 3 将堆栈跟踪写入 tombstoned(带有 android 10 的智能手机)
- ios - 该视图是 Iphone XS Max、Iphone 11 pro max 与不同项目的显示差异
- android - 如何将初始屏幕活动中获取的数据发送到 Kotlin 中的其他活动?
- mongodb - 如何使用 Kubedb 更改或增加部署在 kubernetes 中的 Mongodb 中 PVC/存储的大小
- android - 我想做一个 FloatView,但我不知道如何让它只显示在应用程序中
- css - EventRender 渲染位置错误
- .net-core - AWS SES 验证电子邮件身份