5

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
2
  • 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" Commented Oct 29, 2015 at 15:35
  • 2
    Use raw_input in place of input if you are using python2 Commented Oct 29, 2015 at 15:36

2 Answers 2

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!"
Sign up to request clarification or add additional context in comments.

1 Comment

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!".
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!"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.