我的家庭作业是写一个Python程序,根据每小时工资和工作小时数计算工人的工资。到目前为止,我已经找到了以下代码
#Function
def calculatePay(rateHour,nHours):
if nHours <= 40:
pay = rateHour * nHours
elif nHours < 60:
pay = (rateHour * 40) + ((nHours - 40) * (rateHour * 1.5))
else:
pay = (rateHour * 40) + (20 * (rateHour * 1.5)) + ((nHours - 60) * (rateHour * 2.0))
return pay
#Main Code
pay1 = calculatePay(30, 20)
print('You worked ', nHours, 'hours at a rate of ', ratehour, 'per hour, you will be paid $ ', pay1)
print()
pay2 = calculatePay(15.50, 50)
print('You worked ', nHours, 'hours at a rate of ', ratehour, 'per hour, you will be paid $ ', pay2)
print()
pay3 = calculatePay(11, 70.25)
print('You worked ', nHours, 'hours at a rate of ', ratehour, 'per hour, you will be paid $ ', pay3)
print()
rateHour = int(input('Enter the rate per hour: '))
nHours = int(input('Enter the number of hours worked: '))
pay4 = calculatePay(rateHour,nHours)
print('You worked ', nHours, 'hours at a rate of ', ratehour, 'per hour, you will be paid $ ', pay4)
print()
当我运行它时,我得到以下错误
Traceback (most recent call last):
File "C:\Users\John\Desktop\Python Programming\JohnLissandrello_Homework3.py", line 15, in <module>
print('You worked ', nHours, 'hours at a rate of ', ratehour, 'per hour, you will be paid $ ', pay1)
NameError: name 'nHours' is not defined
我相信这是因为我试图在主代码中使用局部变量rateHour和nHours
如何将这两个变量从函数传递到主代码中,以便将rateHour和NHhours与计算的工资一起输出
您已经将这些值传递给函数,也就是说,它们位于函数外部。问题是:他们没有名字
建议:
如果你看你的代码,你会发现很多重复的行。您可以再次将其放入方法中:
然后在循环中进行:
@Thomas已经找到了答案,但还有几个问题:
第21行及;22您调用了int,但第14行和第17行使它看起来像是要使用浮点
第25行您的费率为每小时21&;24小时——Python对资本化非常挑剔
相关问题 更多 >
编程相关推荐