如何解決此 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
uj5u.com熱心網友回復:
您的代碼片段缺少一些重要的資訊,例如“total_hrs_per_wk”以及呼叫此函式的支持代碼。所以,我使用了一些藝術許可來填補缺失的部分。以下是利用您的加班功能以及一些修訂的代碼片段。
#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_wk”的定義,因此添加了一個計算,通過將工人的正常作業時間與加班時間相加來得出一周的總小時數。
- 由于變數“total_hrs_per_wk”包含一個數值而不是一個字串,因此 print 陳述句被更改為將值列印為數字而不是您最初指定的字串。
- 列印陳述句中的最后一個變數“overtime_pay”被更正為“overtime_p”。“overtime_pay”是您的函式的名稱,列印該值只會列印出函式定義的詳細資訊,而不是您所追求的加班費。
試試看。
補充說明。
為了回應關于“total_hrs_per_week”是一個回傳值而不是變數的函式的評論,下面是一個修改后的代碼片段,它等效于上面的代碼片段,但呼叫了一個名為“total_hrs_per_wk”的函式并使用回傳的值.
# 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
測驗導致終端上顯示相同的值。如前所述,這只是獲得相同結果的眾多方法之一。
uj5u.com熱心網友回復:
你的意思是這里的最后一個變數是overtime_p
?
print('Overtime pay for ' total_hrs_per_wk 'hours worked' 'is: \t', overtime_pay)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506845.html
下一篇:如何使用函式在三元運算中設定值?