Reputation: 1
I am a new python user. I have an issue with the code I am writing. I am supposed to make a weekly pay check program that calculates how much you'll get paid. I also have to account for overtime hours.
This was the instructions given to my teacher -
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.
This is the code I've made for it:
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)
So when I'm in the shell window and run it.
I input: weeklypaycheck(55,10)
ps. '55' is the total hours worked, '10' is how much I get paid per hour
And this is my output: This is your pay: 625.0
My output is supposed to be This is your pay: 650.0
and not This is your pay: 625.0
.
Same goes if input weeklypaycheck(51,20)
I'll output This is your pay 1130.0
My output is supposed to be This is your pay: 1140
and not This is your pay: 1140
.
My math might be off but I'm very confused. If anyone is willing to help me, thank you!
Upvotes: 0
Views: 1131
Reputation:
I refactored the code as suggested above to eliminate the duplicate code, used else
instead of elif
when it made sense, fixed defect for hours == 50
, and introduced a dict h
to logical group the hours break-down:
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}")
There is a different way of thinking about this problem, namely, what the min or max hours for each hours break-down. This yield this implementation (notice that only hours break-down calculation changed):
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}")
and I would test the boundary conditions like this:
for hours in [39, 40, 41, 49, 50, 51]:
weeklypaycheck(hours, 1)
and the results are:
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
Upvotes: 0
Reputation: 1742
You wrote: if hours > 40 or hours < 50
. Ask yourself very carefully what hours satisfy this if. For example, does 60 hours satisfy this? What about 30 hours?
Upvotes: 3