[英]How to make a while loop exit when user enters a certain string?
I am making a survey that asks the user about age, gender, etc., using a while-loop. 我正在做一个调查,使用while循环询问用户年龄,性别等信息。 Is there any way to make the program exit the loop when the user enters certain strings like "cya" or "bye"?
当用户输入某些字符串(例如“ cya”或“ bye”)时,是否有任何方法可以使程序退出循环?
I know that I could make an if-statement after every input, but is there an faster/easier way to do this? 我知道我可以在每次输入后都做一个if语句,但是有一种更快/更容易的方法吗?
Example of what I want to achieve: 我要实现的示例:
while (user has not entered "cya"):
age = int(input("How old? "))
gender = input("gender? ")
EDIT: this example was very short, but the survey i'm making is very long, so testing every variable is too time consuming. 编辑:这个例子很短,但是我正在做的调查很长,因此测试每个变量都非常耗时。
I think the easiest way to perform a survey is to construct a list of all your questions, and then use that to make a dictionary of all your user details. 我认为执行调查的最简单方法是构建所有问题的列表,然后使用该列表编制所有用户详细信息的字典。
details = {}
questions = [("gender", "What is your gender?"), ("age", "How old?"), ("name", "What is your name?")]
response = ""
while response not in ("bye", "cya"):
for detail, question in questions:
response = input(question)
if response in ("bye", "cya"):
break
details[detail] = response
print(details)
Example: 例:
What is your gender?M
How old?5
What is your name?john
{'gender': 'M', 'age': '5', 'name': 'john'}
What is your gender?m
How old?bye
{'gender': 'm'}
It's not a good idea, but one way to achieve what you want is to throw an exception to get out of the loop. 这不是一个好主意,但是实现您想要的目标的一种方法是抛出异常以摆脱循环。
def wrap_input(prompt, exit_condition):
x = raw_input(prompt)
if x == exit_condition:
raise Exception
return x
try:
while True:
age = int(wrap_input("gender ", "cya"))
except Exception:
pass
Edit: If you don't need to exit immediately then a cleaner approach is to provide your own input function which stores all input in a set which can then be checked/reset at each iteration. 编辑:如果您不需要立即退出,那么一种更干净的方法是提供您自己的输入函数,该函数将所有输入存储在一个集中,然后可以在每次迭代时检查/重置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.