leela.fry
leela.fry

Reputation: 299

Python while loop with user input

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

Upvotes: 5

Views: 86842

Answers (2)

user5416120
user5416120

Reputation:

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

Upvotes: 2

Avi&#243;n
Avi&#243;n

Reputation: 8396

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

Upvotes: 11

Related Questions