我有一个简单的小程序,它不起作用。我希望程序不断地向用户询问我的名字,直到他们猜到为止。
程序在第一次尝试后抛出一条错误消息。我搞不清问题出在哪里。
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:UsersAnetaDesktopguess_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!"