Вы можете просто связать 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
Readup: