0

I am currently working through Automate the Boring Stuff with Python and was given this example in Chapter 4 (You can read the page here if you're curious). The code was typed from the example given in the book as suggested and is pasted below. In the book, I am told the response I get is supposed to prompt me to enter a pet name, and if it doesn't match what's in the list I should get a response saying that I don't have a pet by that name.

The problem I run into is that the response I ACTUALLY get is :

Enter a pet name:
Gennie
Traceback (most recent call last):
  File "/Users/gillian/Documents/Python/AutomateTheBoringStuffwithPython/Ch4Example1.py", line 3, in <module>
    name = str(input())
  File "<string>", line 1, in <module>
NameError: name 'Gennie' is not defined

I'm not sure why that would be. I don't see anything different about my code from the example, but something about that error seems not right. Can anyone tell me where I've gone off course?

myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name: ')
name = input()
if name not in myPets:
    print('I do not have a pet named ' + name)
else:
    print(name + ' is my pet.')
DavidG
  • 24,279
  • 14
  • 89
  • 82
DrTaylor
  • 19
  • 5
  • 3
    What version of Python are you using? I bet you're using Python 2.7. The book is probably designed for Python 3, which has slightly different syntax. – Kevin Sep 26 '17 at 14:36
  • 3
    Possible duplicate of [What's the difference between raw\_input() and input() in python3.x?](https://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) – Guillaume Sep 26 '17 at 14:37
  • 1
    `input()` in Python2 will evaluate the given input string, so if you type `Gennie` it will try to replace it with the value of a variable with the same name. This nonsense has been fixed in Python3. – Guillaume Sep 26 '17 at 14:39
  • Also the return value of `input()` in Python3 is already of type `str`, so a cast conversion to `str` isn't really needed. – Torxed Sep 26 '17 at 14:40
  • Use raw_input() it will solve the error. For more info use link provided by @Guillaume Also if you input "Genie" in string format it will work just FYI. – Prashant Shubham Sep 26 '17 at 14:40

1 Answers1

0

Change input() into raw_input() as you seem to be using python 2.x and this code is written in 3.x.

Find out more about differences here.

zipa
  • 27,316
  • 6
  • 40
  • 58