python - 刚开始学习,我的第一个作业被难住了
问题描述
我的任务是制作一个简单的工资计算器。当我运行它时,它要求输入就好了。但是当它到达执行计算的部分时,我得到:
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)
解决方案
就像 trincot 评论的那样,您需要print
作为带括号的函数调用。其他一些注意事项...
- 你不需要括号
20
和.10
- 您不应该使用
eval
来解析输入,使用float
orint
代替 - 由于 * 在操作顺序上高于 +,因此您也不需要在最终计算中使用方括号(但您需要在整个过程中使用方括号才能
print
正确调用)
在您的代码中发生的是print (total_hours*hourly_wage)
调用print
函数并返回None
这是正常的print
,然后 Python 尝试将返回的值添加None
到您的第二对括号(weekly_sales_revenue * commission)
中,这会引发错误,因为添加None
和float
不允许。
当你像这样重新格式化它时,这会更清楚
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)
推荐阅读
- android - Method should have no parameters
- apache-kafka - How to limit number of records in Kafka-consumer
- python - python错误:ModuleNotFoundError:没有名为“NLTK”的模块
- python - How to apply clipping to trainable variables in TensorFlow
- php - 我们如何使用 eloquent 在 laravel 5.4 中选择和更新表?
- selenium - Selenium 中的 DOM 属性值
- angular - 角度-primeng-确认对话框不起作用
- android - 片段已泄漏,尽管已附加
- asp.net - 如果我向网络服务器发出请求,网络服务不会第二次发送数据
- python-datetime - 将数据框的列转换为时间戳