[英]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.