Reputation: 1652
I am going through Python Programming for the Absolute Beginner, Third Edition
and Chapter 4 has some code which gets a user's message and prints the len()
of the message and then tells the user if there is an 'e' in the message:
My code I typed in emulating what is in the book is:
# 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'
When I run it and try it with any phrase or word I am getting the following error:
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
I tried casting message as a str()
by doing str(input('Please enter a message: '))
but that gives the same error as well.
What is causing this? What do I need to do to fix it?
Upvotes: 1
Views: 44
Reputation: 1652
I wrapped the above in a function and passed in the message as a parameter to the function. Works just fine.
# 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')
Upvotes: 0
Reputation: 8547
Change your first line from using input
:
message = input('Please enter a message: ')
to raw_input
.
message = raw_input('Please enter a message: ')
input
actually evaluates the string you pass in, so when you type enter
, Python looks for a variable named enter
, doesn't find it, and gives you an error.
raw_input
just returns the string.
Upvotes: 1