0

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?

  • 2
    Please show us demodata and the code you have, what it outputs now and what you want it to output.copy & paste it into your question, select it and hit Ctrl+k to format as text. – Patrick Artner Nov 04 '18 at 16:05
  • 1
    @PatrickArtner Thanks Patrick! As a new user of this platform and python, you helped me understand my mistake. I have corrected the question now. –  Nov 04 '18 at 16:19
  • 2
    I think your edit (multiple if statements) actually is the best way to solve it. You might want to build up a string containing multiple reasons for failure as the employee may fail for several different criteria. You could do something more complicated using a list of functions each of which may deny qualification and add a reason, and running each function from the list in turn, but that seems overkill for a problem this simple. – Rob Bricheno Nov 04 '18 at 16:26
  • @rbricheno Exactly! Even multiple if statements seem inefficient to me. I thought that there should be some simpler way to do it. –  Nov 05 '18 at 11:30

1 Answers1

2

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:

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
  • Beautiful! But my concern is that I do not want to include def or check function. Can it be done without that? –  Nov 04 '18 at 17:39
  • 1
    @user585380 No. It would involve far too much duplicate code. You can learn about functions here: https://docs.python.org/3/tutorial/controlflow.html#defining-functions – Patrick Artner Nov 04 '18 at 17:46
  • 1
    @user585380 you can collent all this things in a list: `reasons =[]` .. then instead of `print("too ....") do `reasons.append("too ....")` - after all is checked you can see if the list has any items, and if so `if reasons: print "Rejected: ", *reasons` - else print ok or whatever. Empty lists are False, lists with items are True - hence `if reasons:` works. Read about lists here: https://docs.python.org/3/tutorial/introduction.html#lists – Patrick Artner Nov 05 '18 at 16:30
  • 1
    if (age<20): reason.append("too young") –  Nov 05 '18 at 17:45
  • What does this mean: *reasons –  Nov 05 '18 at 17:48
  • if there are two reasons and I want them in a separate line, could I simply do \n? –  Nov 05 '18 at 17:58
  • Please stop using me as personal tutor. You already posted a followup question af https://stackoverflow.com/questions/53154850/how-to-print-the-string-or-value-held-as-true-python - which _also got answered_. No person here on SO will do your job/task for you, you need to learn python yourself. Your questions are very basic and show big knowledge gaps. If you use python professionally, learn it and own it. Use available tutorials - you can find them if you click the [tag:python] or [tag:python-2.7], then click `learn more...` and read - it contains sections of links to learning resources. – Patrick Artner Nov 05 '18 at 18:33