我有一个简单的小程序,但不起作用。我希望程序不断询问用户我的名字,直到他们猜到为止。
程序在第一次尝试后抛出错误消息。我无法弄清楚问题出在哪里。
name = "not_aneta"
while name != "aneta":
name = input("What is my name? ")
if name == "aneta":
print "You guessed my name!"
当我运行它时,我收到一条错误消息:
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
您必须使用
raw_input
(input
尝试将输入作为Python表达式运行,这不是您想要的)并修复缩进问题。
name = "not_aneta"
while name!= "aneta":
name = raw_input("What is my name? ")
if name == "aneta":
print "You guessed my name!"
看来您正在使用 2.x,因此您需要
raw_input
作为字符串。
name = "not_aneta"
while name!= "aneta":
name = raw_input("What is my name? ")
此外,
if
语句毫无意义,因为在用户猜出正确的名称之前程序不会继续。所以你可以这样做:
name = "not_aneta"
while name!= "aneta":
name = raw_input("What is my name? ")
print "You guessed my name!"