我是一个Python新手,写了一个短程序。第一部分有效,但 if 语句部分有回溯/语法?问题。建议?
hours = input("How many hours did you work this week?")
wage = input("How much do you make each hour?")
weeklySalary = hours * wage
print "You made", weeklySalary, "dollars this week."
daily = str(input("Would you like to know your daily average this week?"))
if daily in ['Yes' , 'yes' , 'Y' , 'y']:
print "You averaged", (weeklySalary / 7), "dollars per day."
else:
print "Maybe next week..."
这是错误:
How many hours did you work this week?10
How much do you make each hour?10
You made 100 dollars this week.
Would you like to know your daily average this week?yes
Traceback (most recent call last):
File "/Users/jake/Desktop/Python_U_M/weekly_salary.py", line 5, in <module>
daily = str(input("Would you like to know your daily average this week?"))
File "<string>", line 1, in <module>
NameError: name 'yes' is not defined
问题是
input
正在评估您的输入,因此 eval(y)
会引发错误:
How many hours did you work this week?10
How much do you make each hour?7
You made 70 dollars this week.
Would you like to know your daily average this week?y
Traceback (most recent call last):
File "hmm", line 5, in <module>
daily = str(input("Would you like to know your daily average this week?"))
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
比较:
How many hours did you work this week?10
How much do you make each hour?7
You made 70 dollars this week.
Would you like to know your daily average this week?"y"
You averaged 10 dollars per day.
文档: https://docs.python.org/2/library/functions.html#input
如文档中所述,“考虑使用 raw_input() 函数来处理用户的一般输入。”进行此更改可防止对 'y' 求值,从而将 is 视为字符串,就像您所期望的那样。
问题不会出现在整数上,因为
eval(10)
仍然是 10
。
通过 Python 2.6.5 确认。您的代码可能会在 Python 3 中按原样工作 - Python 3 中的输入文档不包含隐式
eval
: https://docs.python.org/3/library/functions.html#input