# 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
您可以简单地链接
if: elif:
——如果多个“why not's”组合在一起,您就必须具有创造性——或者您可以利用一些函数和列表理解来处理它。你知道吗您可以为每个值创建一个check函数,如果值为ok,则返回
True
,否则返回False
,如果值超出界限,则返回错误消息:将函数应用于某些测试数据:
输出:
读数:
相关问题 更多 >
编程相关推荐