0

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.

2 Answers 2

1

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'}
Sign up to request clarification or add additional context in comments.

3 Comments

But is there a way to do this with a while-loop?
I put up an example of using a while loop. However, it is more complex than the other version, so I highly recommend using the for loop.
Thanks, but when I run your code, the it doesn't loop. It just stops after asking the set of questions once?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.