python上计算加班费的问题

2024-05-23 20:01:41 发布

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

我是一个新的python用户。我写的代码有问题。我应该 制定一个每周工资检查计划,计算你将获得多少工资。我还要说明加班时间

这是给我老师的指示


The first 40 hours you work, you get paid your regular hourly wage. The next 10 hours are overtime and paid to you at 1.5 times your hourly rate. The rest of your hours (greater than 50) is paid to you at twice your hourly rate.

这是我为它编写的代码:


def weeklypaycheck(hours,rate):
    if (hours <= 40):
        pay = hours * rate
        print("This is your pay: ",pay)
    elif hours > 40 or hours < 50:
        nm = 40 * rate
        othours = hours - 40
        otpay = (othours * (rate * 1.5))
        print("This is your pay: ", otpay + nm)
    elif hours > 50:
        nm = 40 * rate
        otpay = (10 * (rate * 1.5))
        othours = hours - 50
        otpay = (othours2 * (rate *2))
        print("This is your pay: ", nm+ otpay + otpay)

所以当我在shell窗口中运行它时。 我输入:weeklypaycheck(55,10)

ps. '55' is the total hours worked, '10' is how much I get paid per hour

这是我的输出:This is your pay: 625.0

我的输出应该是This is your pay: 650.0,而不是This is your pay: 625.0

如果输入weeklypaycheck(51,20)也是如此 我将输出This is your pay 1130.0

我的输出应该是This is your pay: 1140,而不是This is your pay: 1140

我的数学可能不好,但我很困惑。如果有人愿意帮助我,谢谢


Tags: theyouyourrateisthispayprint
2条回答

你写了:if hours > 40 or hours < 50。非常仔细地问问自己,如果满足了这个条件,什么时间是最合适的。例如,60小时是否满足这一要求?30小时怎么样

我按照上面的建议重构了代码以消除重复代码,在合理的情况下使用else而不是elif,修复了hours == 50的缺陷,并引入了dicth来对小时细分进行逻辑分组:

def weeklypaycheck(hours, rate):
    h = {'regular': 0, 'overtime': 0, 'extra': 0}
    if hours <= 40:
        h['regular'] = hours
    else:
        h['regular'] = 40
        if hours <= 50:
            h['overtime'] = hours - 40
        else:
            h['overtime'] = 10
            h['extra'] = hours - 50
    pay = h['regular'] * rate +\
        h['overtime'] * 1.5 * rate +\
        h['extra'] * 2 * rate
    print(f"This is your pay: {pay}")                                                                      

对于这个问题有一种不同的思考方式,即每个小时的最小小时数或最大小时数是多少。这将产生此实现(请注意,只有小时细分计算更改):

def weeklypaycheck(hours, rate):
    h = {
            'regular': min(hours, 40),
            'overtime': max(min(hours - 40, 10), 0),
            'extra': max(hours - 50, 0)
    }
    pay = h['regular'] * rate +\
        h['overtime'] * 1.5 * rate +\
        h['extra'] * 2 * rate
    print(f"This is your pay: {pay}")

我会测试这样的边界条件:

for hours in [39, 40, 41, 49, 50, 51]:
    weeklypaycheck(hours, 1)

结果是:

This is your pay: 39.0
This is your pay: 40.0
This is your pay: 41.5
This is your pay: 53.5
This is your pay: 55.0
This is your pay: 57.0

相关问题 更多 >