0

I'm trying to create a for loop that prompts the user for a hobby 3 times, then appends each one to hobbies.

Here's what I've come up with so far:

hobbies = []

for tries in range(3):
    hobby = raw_input(input("what's your favorite hobby?: "))
    hobbies.append(hobby)

After I enter a response at the user input prompt, let's say for example my response is "competitive eating", I get the following error in Terminal:

Traceback (most recent call last):
  File "hobbyprompt.py", line 12, in <module>
    hobby = raw_input(input("what's your favorite hobby?: "))
  File "<string>", line 1, in <module>
NameError: name 'competitive eating' is not defined

I'm sure I'm making a really stupid mistake here, but I can't seem to figure out what I'm doing wrong.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
AdjunctProfessorFalcon
  • 1,790
  • 6
  • 26
  • 62

2 Answers2

3

input is equivalent to eval(raw_input). It's completely redundant in your example. Just drop it and keep the raw_input only:

hobby = raw_input("what's your favorite hobby?: ")

EDIT:
To answer the question in the comments, input takes the string and attempts to evaluate it as a python expression (see eval's documentation for details). Since "competitive eating" is not variable you've already defined, it cannot be evaluated, and hence the NameError.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • thanks for the explanation, I know it's an error on my part but can you explain why, if you have raw_input(input("what's your favorite hobby?: ")) it gives the NameError ? What's the erroneous logic that I created there? – AdjunctProfessorFalcon May 17 '15 at 19:17
  • @ChrisPurrone see my edited answer with the details. – Mureinik May 17 '15 at 19:20
  • Ok, thanks for the edited explanation! So basically, by inserting "input" into the statement it's checking to see if the user input matches a pre-defined string? – AdjunctProfessorFalcon May 17 '15 at 20:57
1

You only need raw_input, not input followed by raw_input. Use

hobby = raw_input("what's your favorite hobby?: ")

In python 3.x, input does what raw_input did in previous versions. But prior to Python 3, input, in addition to reading a line from stdin, evaluated that line as if it were a valid Python expression. raw_input is the alternative, so you should use one or the other-- not both. Here, raw_input is appropriate.

nymk
  • 3,323
  • 3
  • 34
  • 36
Bradley Garagan
  • 155
  • 1
  • 9