我有这个简单的小程序,它不起作用。我希望程序不断询问用户我的名字,直到他们猜到。
程序在第一次尝试后抛出错误消息。我无法解决问题所在。
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
答案 0 :(得分:7)
你必须使用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!"
答案 1 :(得分:1)
您似乎正在使用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!"