TypeError:float()参数必须是字符串或数字

时间:2014-10-11 00:40:37

标签: python

我在高中学习11年级的计算机科学,我刚开始用Python学习。我应该创建一个名为computepay的函数,它会询问用户他们的姓名,工资和当周的工作时间,并自动计算总数,包括任何加班时间,而不包括错误输入时的错误。我为所有输入创建了不同的函数,但当我将它全部插入我的computepay函数时,它会告诉我:

  

TypeError:float()参数必须是字符串或数字

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()

2 个答案:

答案 0 :(得分:1)

这些功能都没有返回任何内容

name = getname()    
wage = getwage()    
hours = gethours()

所以他们最终都成为None

试试这个

def getname():
    return input("What's your name?")  # input of name

def getwage():
    wage = input("Hello there! How much money do you make per hour?")  # input
    return float(wage)

def gethours():
    hours = input("Thanks, how many hours have you worked this week?")
    return float(hours)

答案 1 :(得分:1)

错误消息告诉您的是某处(在您未向我们展示的错误消息部分中报告的行号上)您正在调用float并且给它一个既不是数字也不是字符串的参数(即输入)。

你能追踪到这发生的地方吗?

提示:任何不返回任何内容的Python函数(带有return关键字)都会隐式返回None(既不是字符串也不是数字)。