带有用户输入的 Python while 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33418482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python while loop with user input
提问by leela.fry
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
采纳答案by Avión
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.
您必须使用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!"
回答by Avión
It seems that your are using 2.x so you need raw_input
for strings.
似乎您使用的是 2.x,因此您需要raw_input
字符串。
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:
此外,这些if
语句也毫无意义,因为在用户猜出正确名称之前,程序不会继续运行。所以你可以这样做:
name = "not_aneta"
while name!= "aneta":
name = raw_input("What is my name? ")
print "You guessed my name!"