Reputation:
I need to code in python in order to select or not select some employees for a pension program. I will be selecting on the basis of age and nationality So I don't want to select an employee whose age and nationality don't meet some criteria.
I can create a simple if statement and then print out qualified or disqualified, based on my data.
The catch is that I need to print a line which states that the person was disqualified because of being too young or old. How do I assign the criteria the employee has missed in my if statement? If I want to write a statement like this: The employee is not selected because the person doesn't fulfil the criteria: for example, too tall and underweight. How do I insert those in that statement?
Upvotes: 0
Views: 262
Reputation: 51683
You can simply chain if: elif:
- you would have to get creative if multiple "why not's" come together - or you can leverage some functions and list-comprehensions to deal with it.
You can create a check-function for each value thats returns you True
if its ok, else False
and a error message if its out of bounds:
# 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")
Apply function to some test data:
# 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
Output:
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:
Upvotes: 2