我在11年級的計算機科學高中,我剛剛開始用Python。我應該做一個叫computepay
的函數,這個函數會詢問用戶他們的姓名,他們的工資和他們在這個星期的小時數,並自動計算總數,包括任何加班時間,並且當包含錯誤的輸入時不會誤報。我對所有的輸入做出不同的功能,但是當我插上這一切到我computepay
功能它告訴我:TypeError:float()參數需要是一個字符串或數字
TypeError: float() argument must be a string or a number
def mainloop(): #Creating a loop so it doesn't error out.
response = input('Make another calculation?[y/n]') #inputing loop
if response == 'n': #creating input for n
return
if response == 'y':
computepay()
else:
print("\n")
print ("Incorrect input. .")
mainloop()
def getname():
name = input ("What's your name?") #input of name
def getwage():
wage = input ("Hello there! How much money do you make per hour?") #input
try:
float(wage) #Making it so it does not error out when a float
except:
print ("Bad Input")
getwage()
def gethours():
hours = input ("Thanks, how many hours have you worked this week?")
try:
float(hours) #Making it so it does not error out when a float
except:
print("Bad Input")
gethours()
def computepay():
name = getname()
wage = getwage()
hours = gethours()
if float(hours) > float(40):
newhours = float(hours) - float (40) #figuring out the amount of overtime hours the person has worked
newwage = float (wage) * float (1.5) #figuring out overtime pay
overtimepay = float (newwage) * float (newhours) #calculating overtime total
regularpay = (float(40) * float (wage)) + overtimepay #calculating regular and overtime total.
print (name,",you'll have made $",round(regularpay,2),"this week.")
else:
total = float(wage) * float(hours)
print (name,",you'll have made $",round (total,2),"this week.")
mainloop() #creating the loop.
#-------------------------------------------------------------------------------
computepay()
看到發生了什麼事情有點令人困惑,因爲代碼格式化了它,但錯誤消息爲您提供了尋找內容的提示 - 'TypeError:float()參數必須是字符串或數字'。在你浮動的一個呼叫中(例如浮動(工資)),你傳遞的東西(比如工資)不能轉換爲數字。 我建議你打印出每個變量,看看裏面有什麼東西 - 所以,在'wage = getwage()'之後再增加一行'print(wage) – 2014-10-11 00:45:42