7

I have this simple little program which doesn't work. I want the program to keep asking the user for my name till they guess it.

The program throws an error message after the first attempt. I can't work it out where the problem is.

name = "not_aneta"

while name != "aneta":
    name = input("What is my name? ")

if name == "aneta":
    print "You guessed my name!"

When I run it I get an error message:

Traceback (most recent call last):
  File "C:\Users\Aneta\Desktop\guess_my_name.py", line 4, in <module>
    name = input("What is my name? ")
  File "<string>", line 1, in <module>
NameError: name 'aneta' is not defined
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
leela.fry
  • 283
  • 2
  • 3
  • 13
  • 2
    You are using python 2.X and need to use `raw_input`.The `input` function in python 2.X will evaluated the input, so it have raised `NameError` when you wanted to use it in `name == "aneta"` – Mazdak Oct 29 '15 at 15:35
  • 2
    Use `raw_input` in place of `input` if you are using python2 – Ahsanul Haque Oct 29 '15 at 15:36

2 Answers2

11

You have to use raw_input (input tries to run the input as a python expression and this is not what you want) and fix the indentation problem.

name = "not_aneta"

while name!= "aneta":
    name = raw_input("What is my name? ")

    if name == "aneta":
        print "You guessed my name!"
Avión
  • 7,963
  • 11
  • 64
  • 105
  • 5
    Actually we don't need `if` here. You can put `print "You guessed my name!"` outside the `while` loop. Or for more clear, you can use `else` like `else: print "You guessed my name!"`. – Remi Guan Oct 29 '15 at 15:39
2

It seems that your are using 2.x so you need raw_input for strings.

name = "not_aneta"

while name!= "aneta":
    name = raw_input("What is my name? ")

also, the if statements is pretty pointless because the program won't continue until the user guesses the correct name. So you could just do:

name = "not_aneta"

while name!= "aneta":
    name = raw_input("What is my name? ")

print "You guessed my name!"