使用Python input()调用从用户读取NameError

时间:2014-06-13 21:49:52

标签: python string if-statement

我是一名蟒蛇新手并写了一个简短的程序。第一部分可以工作,但if语句部分有一个traceback /语法?问题。建议?

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

1 个答案:

答案 0 :(得分:2)

问题是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”进行评估,因此将处理视为字符串,就像您期望的那样。

问题没有在整数上显示,因为eval(10)仍然是10

通过Python 2.6.5确认。您的代码可能在Python 3中按原样运行 - 在Python 3中输入的文档不包含隐式evalhttps://docs.python.org/3/library/functions.html#input