【问题标题】:Why do I get an unsupported error for +: float and str?为什么我会收到 +: float 和 str 不支持的错误?
【发布时间】:2021-01-21 22:35:08
【问题描述】:

我对编程很陌生,遇到了一个问题。

Traceback (most recent call last):
  File "C:/Users/aecas/AppData/Local/Programs/Python/Python38-32/Project.py", line 24, in <module>
    finalpay = usercommission + userpay
TypeError: unsupported operand type(s) for +: 'float' and 'str'

我写的程序是:

#Prompt user for name
username = input("What is your employee name?")

#Prompt user to enter number of hours worked
userhours = input("Please enter number of hours worked this week: ")


#Prompt user for weekly sales
usersales = input("Enter weekly sales amount:")

commission = float(usersales)

#calculate the commission (.2*user sales input)
usercommission = (20/100) * commission

#hourly rate which I establish
rate = 15

#User pay before commmission
userpay=  (rate * userhours)

#Compute total pay for user
finalpay = usercommission + userpay

print(name, "Your total pay is: ",finalpay)

【问题讨论】:

标签: python typeerror


【解决方案1】:

您需要将userhours 转换为整数。 userhours = int(userhours)也是如此。

【讨论】:

    【解决方案2】:

    很容易理解你的问题,它说“TypeError: unsupported operand type(s) for +: 'float' and 'str'”,这意味着你的第一个值是'float',你的第二个是'string'

    查看代码时,将第一个输入转换为浮点数,而不是 userhours。当您将字符串与如下数字相乘时:userpay= (rate * userhours)。您的字符串userhours 将在userpay 出现重复字符串。因此,首先转换userhours。然后就可以添加了。

    【讨论】:

      【解决方案3】:

      input 正在返回一个字符串,而不是一个浮点数。 usersales 被转换为 float(),但 userhours 永远不会被转换。

      另外,在最后一行,name 将是未定义的,认为它需要是username

      试试这个:

      #!/usr/bin/python3
      #Prompt user for name
      username = input("What is your employee name?")
      
      #Prompt user to enter number of hours worked
      userhours = float(input("Please enter number of hours worked this week: "))
      
      
      #Prompt user for weekly sales
      usersales = input("Enter weekly sales amount:")
      
      commission = float(usersales)
      
      #calculate the commission (.2*user sales input)
      usercommission = (20/100) * commission
      
      #hourly rate which I establish
      rate = 15
      
      #User pay before commmission
      userpay=  (rate * userhours)
      
      #Compute total pay for user
      finalpay = usercommission + userpay
      
      
      print(username, "Your total pay is: ",finalpay)
      

      【讨论】:

      • @alfredocastro - 很高兴我能帮上忙。如果这回答了您的问题,请考虑投票/接受答案,谢谢
      猜你喜欢
      • 2019-12-25
      • 2019-11-23
      • 1970-01-01
      • 2021-08-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2018-03-31
      相关资源
      最近更新 更多