我正在读取一个包含员工信息的文件。名字、姓氏、工作时间、小时工资。我需要计算固定工资,所以小时工资 * 0 到 40 之间(包括在内)的小时数。另外,时间在 41 到 45 之间,包括在内。我的问题是如何只使用 0 到 40 之间的时间来获得正常工资?这是我当前的代码:
def main():
print()
print("This program will compute payroll.")
print("Written by Josh Sollenberger.")
print()
filename = input("Please enter the emplyee file name: ")
infile = open(filename, 'r')
print()
for line in infile:
first,last,hours,wage = line.split(',')
while int(hours) >= 0 and int(hours) <= 40:
regPay = float(wage)*hours
print(first,last,hours,wage,regPay)
主要()
这告诉我我在分配前引用了 regPay。
请您参考如下方法:
我以前用 min 和 max 做过这个
regPay = float(wage) * min(int(hours),40)
# min(hours,40) will return hours, unless hours > 40 then it will return 40
OTpay = float(wage) * OVERTIMERATE * max(int(hours)-40,0)
# max(hours-40,0) will return hours-40, unless hours <= 40 then it will return 0
它告诉您在赋值前引用 regPay 的原因是因为您只会到达 regPay = float(wage)*hours 行(即当 int(hours) 介于 0 和 40 之间时分配 regPay)。如果它 >= 41,它永远不会进入那里!
这个版本的代码永远不要做的令人难以置信的是:
OVERTIMERATE = 1.5 # maybe 2?
first,last,hours,wage = line.split(',')
hours, wage = int(hours), float(wage) # Decimal is better here, but...
OTpay, regPay = 0,0 # initialize
while hours > 40:
hours -= 1
OTpay += wage*OVERTIMERATE
while hours > 0:
hours -= 1
regPay += wage
根据评论编辑
reg_hours = min(int(hours), 40)
timeandhalf_hours = min(max(int(hours)-reg_hours),0),5)
doubletime_hours = max(int(hours) - (reg_hours + timeandhalf_hours), 0)
regPay = float(wage) * reg_hours
timeandhalfPay = float(wage) * 1.5 * timeandhalf_hours
doubletime_hours = float(wage) * 2 * doubletime_hours
还是长格式:
total_pay = 0
hours = int(hours)
wage = float(wage)
for i in range(1,hours+1):
if i <= 40:
total_pay += wage
elif i <= 45:
total_pay += wage * 1.5
else:
total_pay += wage * 2
