首页 > 解决方案 > 刚开始学习,我的第一个作业被难住了

问题描述

我的任务是制作一个简单的工资计算器。当我运行它时,它要求输入就好了。但是当它到达执行计算的部分时,我得到:

Traceback (most recent call last):
  File "C:/Users/werpo/AppData/Local/Programs/Python/Python38-32/Wage Calculator.py", line 17, in <module>
    print (total_hours*hourly_wage)+(weekly_sales_revenue * commission)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'

这是实际的代码。

#Ask how many hours the employee worked this week and assign that value to a varaible
prompt = "How many hours did you work this week?"
total_hours = eval(input(prompt))

#Ask how much revenue the employees total sales for the week brought in

prompt = "How much revenue did your weekly  sales bring in?"
weekly_sales_revenue = eval(input(prompt))

#assign hourly wage and commision rate to their own variables

hourly_wage = (20)
commission = (.10)

#perform calculation for total pay as number of hours worked times hourly wage plus commision revenue times commission rate

print (total_hours*hourly_wage)+(weekly_sales_revenue * commission)

标签: python

解决方案


就像 trincot 评论的那样,您需要print作为带括号的函数调用。其他一些注意事项...

  1. 你不需要括号20.10
  2. 您不应该使用eval来解析输入,使用floatorint代替
  3. 由于 * 在操作顺序上高于 +,因此您也不需要在最终计算中使用方括号(但您需要在整个过程中使用方括号才能print正确调用)

在您的代码中发生的是print (total_hours*hourly_wage)调用print函数并返回None这是正常的print,然后 Python 尝试将返回的值添加None到您的第二对括号(weekly_sales_revenue * commission)中,这会引发错误,因为添加Nonefloat不允许。

当你像这样重新格式化它时,这会更清楚 print(total_hours*hourly_wage) + (weekly_sales_revenue * commission)

这是我的笔记更改的代码:

#Ask how many hours the employee worked this week and assign that value to a varaible
prompt = "How many hours did you work this week?"
total_hours = float(input(prompt))

#Ask how much revenue the employees total sales for the week brought in

prompt = "How much revenue did your weekly  sales bring in?"
weekly_sales_revenue = float(input(prompt))

#assign hourly wage and commision rate to their own variables

hourly_wage = 20
commission = .10

#perform calculation for total pay as number of hours worked times hourly wage plus commision revenue times commission rate
print(total_hours*hourly_wage + weekly_sales_revenue * commission)

推荐阅读