如何根据ifelse语句的结果对一个变量使用多个值?

2024-09-30 01:26:35 发布

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

在下面的代码示例中,我希望使deductions等于4个值中的一个,具体取决于用户输入的输入(查看if else语句)。这可能吗?你知道吗

deductions1 = 0.12 + 0.04 + 0.01 + 0.06
deductions2 = 0.20 + 0.07 + 0.03 + 0.06
deductions3 = 0.30 + 0.09 + 0.05 + 0.06
deductions4 = 0.38 + 0.11 + 0.07 + 0.06
deductions = monthly_salary = hours_worked * hourly_pay

if monthly_salary < 4000:
    deduction_rate = deductions1
elif monthly_salary >= 4000 and monthly_salary < 8000:
    deduction_rate = deductions2
elif monthly_salary >= 8000 and monthly_salary < 16000:
    deduction_rate = deductions3
else:
    deductions = deductions4

net_salary = monthly_salary - (deductions * monthly_salary)

Tags: and代码示例ifrateelsesalaryelif
2条回答

这可能就是你想做的吗?地址:

if monthly_salary < 4000:
    deductions = 0.12 + 0.04 + 0.01 + 0.06
elif monthly_salary >= 4000 and monthly_salary < 8000:
    deductions = = 0.20 + 0.07 + 0.03 + 0.06
elif monthly_salary >= 8000 and monthly_salary < 16000:
    deductions =  0.30 + 0.09 + 0.05 + 0.06
else:
    deductions =  0.38 + 0.11 + 0.07 + 0.06


net_salary = monthly_salary - (deductions * monthly_salary)

您可以简化它,您不需要elifs的下限-如果早一点匹配elsewise。你知道吗

def getDeductions(salary):
    """Returns deductions based on given salary."""
    deductions1 = 0.12 + 0.04 + 0.01 + 0.06
    deductions2 = 0.20 + 0.07 + 0.03 + 0.06
    deductions3 = 0.30 + 0.09 + 0.05 + 0.06 
    deductions = 0.38 + 0.11 + 0.07 + 0.06  # default for >= 16k

    # lower deductions based on salary if less then 16k

    if monthly_salary < 4000:
        deductions = deductions1
    elif monthly_salary < 8000:        # lower border not needed, if would have matched
        deductions = deductions2
    elif monthly_salary < 16000:       # lower border not needed, if would have matched
        deductions = deductions3  

    return deductions



hours_worked = float(input("Hours:"))
hourly_pay = float(input("Pay per hour:"))

monthly_salary = hours_worked * hourly_pay

net_salary = monthly_salary - (getDeductions(monthly_salary) * monthly_salary)
print(net_salary)

输入:343(h)和12(pay/h),输出:

2634.24

通过将其分解成一个方法,您可以将决策过程从主代码中封装出来,并使其“更精简”。具体细节在您的函数中清晰可见。你知道吗

相关问题 更多 >

    热门问题