名称错误,不确定原因

时间:2014-03-20 01:46:30

标签: python-2.7

我正在浏览Python Programming for the Absolute Beginner, Third Edition,第4章有一些代码可以获取用户的消息并打印消息的len(),然后告诉用户消息中是否有“e”:

我输入的代码模仿书中的内容是:

# Message Analyzer
# Demonstrates the len() operator and the in operator

message = input('Please enter a message: ')
print ('The length of your message is: ', len(message))
print 'The most common letter in the English language, \'e\','
if "e" in message:
    print ('is in your message.')
else:
    print 'is not in your message'

当我运行它并使用任何短语或单词尝试时,我收到以下错误:

Please enter a message: enter
Traceback (most recent call last):
File "/Users/daddy/PycharmProjects/python_programming_exercises/chapter 4 - message analyzer.py", line 5, in <module>
message = input('Please enter a message: ')
File "<string>", line 1, in <module>
NameError: name 'enter' is not defined

我尝试通过str()将邮件投射为str(input('Please enter a message: ')),但同样也会出错。

造成这种情况的原因是什么?我需要做些什么来解决它?

2 个答案:

答案 0 :(得分:1)

使用input更改第一行:

message = input('Please enter a message: ')

raw_input

message = raw_input('Please enter a message: ')

input实际上会计算您传入的字符串,因此当您键入enter时,Python会查找名为enter的变量,但找不到它,并且会给您一个错误。

raw_input只返回字符串。

答案 1 :(得分:0)

我将上面的内容包装在函数中,并将消息作为参数传递给函数。工作得很好。

# Message Analyzer
# Demonstrates the len() operator and the in operator


def message_analyzer(message):

    print ('The length of your message is: ', len(message))
    print 'The most common letter in the English language, \'e\','
    if "e" in message:
        print ('is in your message.')
    else:
        print 'is not in your message'

message_analyzer('The quick brown fox jumps over the lazy dog')