Python 如何根据if-else语句的结果为一个变量使用多个值?
在下面的代码示例中,我想使Python 如何根据if-else语句的结果为一个变量使用多个值?,python,python-3.x,if-statement,Python,Python 3.x,If Statement,在下面的代码示例中,我想使扣减等于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 = hour
扣减
等于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)
扣减1=0.12+0.04+0.01+0.06
扣除额2=0.20+0.07+0.03+0.06
扣除额3=0.30+0.09+0.05+0.06
扣除额4=0.38+0.11+0.07+0.06
扣除额=月工资=工作小时数*小时工资
如果月薪<4000:
扣除率=扣除额1
elif月薪>=4000,月薪<8000:
扣除率=扣除额2
elif月薪>=8000,月薪<16000:
扣除率=扣除额3
其他:
扣除额=扣除额4
净工资=月工资-(扣除额*月工资)
这可能就是你想要做的吗
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)
如果月薪<4000:
扣除额=0.12+0.04+0.01+0.06
elif月薪>=4000,月薪<8000:
扣除额==0.20+0.07+0.03+0.06
elif月薪>=8000,月薪<16000:
扣除额=0.30+0.09+0.05+0.06
其他:
扣除额=0.38+0.11+0.07+0.06
净工资=月工资-(扣除额*月工资)
您可以简化它,您不需要elifs的下限-更早的if会匹配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)
通过将其分解成一个方法,您可以将决策过程从主代码中封装出来,并使其“更精简”。具体细节在您的函数中清晰可见。扣减率是否应该是扣减?您发布的代码有什么问题?这正是你们想要的,不是吗?gps的答案正是我想要的,我是一个没有注意到这一点的白痴。谢谢你们,太好了!我很愚蠢,如果你认为这个答案有用,请投票——很多人都感谢我,但因为我是新来的,所以我得到了这个(感谢你的反馈!记录了声誉低于15的人的投票,但不要改变公开显示的帖子分数。)
2634.24