python - 打印中的python分配
问题描述
我需要在 python 中编写代码,以便为养老金计划选择或不选择一些员工。我将根据年龄和国籍进行选择所以我不想选择年龄和国籍不符合某些标准的员工。
我可以创建一个简单的 if 语句,然后根据我的数据打印出合格或不合格。
问题是我需要打印一条线,说明该人因太年轻或太老而被取消资格。如何分配员工在我的 if 语句中遗漏的标准?如果我想写这样的陈述:该员工未被选中,因为该人不符合标准:例如,太高和体重不足。我如何在该语句中插入这些?
解决方案
您可以简单地链接if: elif:
- 如果多个“为什么不”聚集在一起,您将不得不发挥创造力 - 或者您可以利用一些功能和列表理解来处理它。
您可以为每个返回的值创建一个检查函数,True
如果它是好的,否则False
如果它超出范围则返回一个错误消息:
# generic checker function
def check(param, min_val, max_val, min_val_error,max_val_error):
"""Checks 'param' agains 'min_val' and 'max_val'. Returns either
'(True,None)' or '(False, correct_error_msg)' if param is out of bounds"""
if min_val <= param <= max_val:
return (True,None) # all ok
# return the correct error msg (using a ternary expression)
return (False, min_val_error if param < min_val else max_val_error)
# concrete checker for age. contains min/max values and error messages to use for age
def check_age(age):
return check(age,20,50,"too young","too old")
# concrete checker for height, ...
def check_height(height):
return check(height,140,195,"too short","too long")
# concrete checker for weight, ...
def check_weight(weight):
return check(weight,55,95,"too thin","too heavy")
对一些测试数据应用函数:
# 3 test cases, one all below, one all above, one ok - tuples contain (age,height,weight)
for age,height,weight in [ (17,120,32),(99,201,220),(30,170,75)]:
# create data
# tuples comntain the thing to check (f.e. age) and what func to use (f.e. check_age)
data = [ (age,check_age), (height,check_height), (weight,check_weight)]
print(f"Age: {age} Height: {height} Weight: {weight}")
# use print "Age: {} Height: {} Weight: {}".format(age,height,weight) for 2.7
# get all tuples from data and call the func on the p - this checks all rules
result = [ func(p) for p,func in data]
# if all rule-results return (True,_) you are fine
if all( r[0] for r in result ):
print("All fine")
else:
# not all are (True,_) - print those that are (False,Message)
for r in result:
if not r[0]:
print(r[1])
# use print r[1] for python 2.7
输出:
Age: 17 Height: 120 Weight: 32
too young
too short
too thin
Age: 99 Height: 201 Weight: 220
too old
too long
too heavy
Age: 30 Height: 170 Weight: 75
All fine
阅读:
推荐阅读
- jenkins - Groovy 脚本因系统 groovy 而失败
- c - c循环函数计算时间复杂度
- php - Laravel 发布数据
- javascript - 在 Formik 中提交嵌套表单
- javascript - 使用 ngx-translate 以 Angular 10 转换动态字符串
- mysql - 通过匹配值重新组合数据
- javascript - dc.js:区域选择自动选择它刷过的所有图表的整个图表范围
- android - MvxFragment 进入动画
- laravel-7 - 如何在 Laravel Framework 7.29.3 中解析 laravel ui
- web-testing - 当我没有输入类型 = 文件时如何使用 testRigor 上传文件?