Ali Mustafa
Ali Mustafa

Reputation: 565

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. Is there any way to make the program exit the loop when the user enters certain strings like "cya" or "bye"?

I know that I could make an if-statement after every input, but is there an faster/easier way to do this?

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.

Upvotes: 0

Views: 577

Answers (2)

icedtrees
icedtrees

Reputation: 6466

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'}

Upvotes: 1

kyrre
kyrre

Reputation: 646

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.

Upvotes: 0

Related Questions