pythonwhile-loopuser-input

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

Solution

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