[英]How to fix TypeError: unsupported operand type(s) for *: 'instance' and 'float' in a function
[英]How do I fix this error: TypeError: unsupported operand type(s) for *: 'float' and 'function' in python
如何解决此 TypeError
TypeError: unsupported operand type(s) for *: 'float' and 'function'
这是我的代码:
#calculate overtime pay
def overtime_pay(weekly_pay, regular_rate, overtime_hrs ):
overtime_p = weekly_pay + ((regular_rate*1.5)*overtime_hrs)
print('Overtime pay for ' + total_hrs_per_wk + 'hours worked' + 'is: \t', overtime_pay)
return overtime_p
您的意思是这里的最后一个变量是overtime_p
吗?
print('Overtime pay for ' + total_hrs_per_wk + 'hours worked' + 'is: \t', overtime_pay)
您的代码片段缺少一些重要信息,例如“total_hrs_per_wk”以及调用此 function 的支持代码。 所以,我使用了一些艺术许可来填补缺失的部分。 以下是利用您的加班 function 以及一些修订的代码片段。
#calculate overtime pay
def overtime_pay(weekly_pay, regular_rate, overtime_hrs ):
total_hrs_per_wk = float(weekly_pay / regular_rate + overtime_hrs) # This variable was missing - added it
overtime_p = weekly_pay + ((regular_rate*1.5)*overtime_hrs)
print('Total pay with overtime for ', total_hrs_per_wk, 'hours worked is: \t', overtime_p) # Made the last variable "overtime_p" instead of the function name
return overtime_p
# Created the following code to execute the function with floating point variables
weekly_pay = float(input("Enter weekly pay: "))
regular_rate = float(input("Enter worker rate: "))
overtime_hrs = float(input("Enter overtime hours: "))
overtime_pay(weekly_pay, regular_rate, overtime_hrs)
以下是从代码片段中删除的一些内容。
试试看。
补充说明。
为了回应关于“total_hrs_per_week”是一个返回值而不是变量的 function 的评论,下面是一个修改后的代码片段,它等效于上述代码片段,但调用名为“total_hrs_per_wk”的 function 并使用返回的值.
# Have total weekly hours as a function instead of a variable
def total_hrs_per_wk(pay, reg_rate, total_hrs):
return float(total_hrs - pay / reg_rate)
#calculate overtime pay
def overtime_pay(weekly_pay, regular_rate, overtime_hrs ):
total_hr = float(weekly_pay / regular_rate + overtime_hrs)
overtime_p = weekly_pay + ((regular_rate*1.5)*overtime_hrs)
print('Total pay with overtime for ', total_hr, 'hours worked is: \t', overtime_p) # Made the last variable "overtime_p" instead of the function name
return overtime_p
# Created the following code to execute the function with floating point variables
weekly_pay = float(input("Enter weekly pay: "))
regular_rate = float(input("Enter worker rate: "))
overtime_hrs = float(input("Enter overtime hours: "))
overtime_pay(weekly_pay, regular_rate, total_hrs_per_wk(weekly_pay, regular_rate, (40 + overtime_hrs))) # Last parameter will be the result of a function call
测试导致终端上显示相同的值。 如前所述,这只是获得相同结果的众多方法之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.