I am attempting to write a program that calculates pay, with the option of overtime for more than 40 hours at $10/hour. Currently it looks like this:
hrs = input("Enter Hours: ")
h = float(hrs)
rate = input("Enter Rate: ")
r = float(rate)
if h > 40:
reg = h * r
otp = (h - 40) * (r * 1.5)
final_otp = reg + otp
print("Pay:",final_otp)
else:
reg_pay = h * r
print("Pay:",reg_pay)
The problem is that when using this specific method, it causes regular pay at overtime to be 450 when it is really 400, adding 75 for overtime giving a total of 525. One solution would be to change the overtime rate formula to 0.5, but this doesn't really make sense to me and I would like to see it done using a rate of 1.5. How do I correct it while still multiplying by the 1.5 rate?
I put in 0.5 for the OT rate multiplier but I'd like to see how it can be done without doing so. I don't do very well at math so if I were to make a more complex version of this, I wouldn't know how to correct the OT rate in the formula to compensate.
It looks like you are focusing too hard on the derivation of the regular pay when the entered hours exceeds the normal threshold for calculating overtime. After reviewing and testing your code, following is a refactored version of your program with some small tweaks to make it a bit more robust.
ot_level = 40
print("Enter hours and rate to calculate payroll or enter \"q\" to end payroll")
while True:
hrs = input("Enter Hours: ")
if hrs == 'q':
break
h = float(hrs)
rate = input("Enter Rate: ")
r = float(rate)
if h > ot_level:
reg = ot_level * r # Just multiply the normal pay hours value by the rate for regular pay
print("Regular pay:", reg)
otp = (h - ot_level) * (r * 1.5)
print("Overtime:", otp)
final_otp = reg + otp
print("Pay with overtime:",final_otp)
else:
reg_pay = h * r
print("Pay:",reg_pay)
Following are some items to note.
With those bits of refactoring, following was the test output at the terminal.
@Vera:~/Python_Programs/Payroll$ python3 Payroll.py
Enter hours and rate to calculate payroll or enter "q" to end payroll
Enter Hours: 40
Enter Rate: 10
Pay: 400.0
Enter Hours: 45
Enter Rate: 10
Regular pay: 400.0
Overtime: 75.0
Pay with overtime: 475.0
Enter Hours: 42
Enter Rate: 12
Regular pay: 480.0
Overtime: 36.0
Pay with overtime: 516.0
Enter Hours: q
Go ahead and evaluate this refactored code and see if it meets the spirit of your project.