prin中的python赋值

2024-05-13 06:07:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用python编写代码,以便为养老金计划选择或不选择一些员工。 我会根据年龄和国籍来选择 所以我不想选择年龄和国籍不符合某些标准的员工。你知道吗

我可以创建一个简单的if语句,然后根据我的数据打印出qualified或unqualified。你知道吗

问题是,我需要打印一行,说明该人被取消资格,因为太年轻或太老。如何分配员工在if语句中遗漏的标准? 如果我想写一个这样的声明:这个员工没有被选中,因为这个人不符合标准:例如,太高和体重不足。 我该如何在声明中插入这些内容?你知道吗


Tags: 数据代码声明标准if员工语句计划
1条回答
网友
1楼 · 发布于 2024-05-13 06:07:33

您可以简单地链接if: elif:——如果多个“why not's”组合在一起,您就必须具有创造性——或者您可以利用一些函数和列表理解来处理它。你知道吗


您可以为每个值创建一个check函数,如果值为ok,则返回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

读数:

相关问题 更多 >