Anna Harvey
Anna Harvey

Reputation: 21

Create dictionary from user input with if/then statements in Python

New Python learner here. I've looked all over for assistance but I can't seem to find a solution to my problem. I want to create a dictionary from user input, but for some of the variables, I would like to include if/then or while statements in order to skip questions that are irrelevant based on the user input. Here is an example of my code so far:

    input_dict = {'var1': input('Question 1:\n'),
                  'var2': input('Question 2:\n'),
                  'var3': input('Question 3:\n'),
                  'var4': input('Question 4:\n')}

What I'd like to do is create a loop where if the answer to Question 3 is 'no', then it would skip question 4.

I also realize that I may be approaching this problem incorrectly. The end goal is to create a dataframe of information from the user input.

Upvotes: 1

Views: 90

Answers (3)

lemonhead
lemonhead

Reputation: 5518

The most expedient way is to perhaps hardcode these interactions (see @Andrej's answer for a good example of this).

However, following along with your somewhat "procedural"/configurable dictionary approach (e.g. something you could later read in from a file, etc.), that is easily tunable you just need a simple data structure which would capture the dependencies between different questions, maybe even with a default to use if a question is skipped. Then you could simply ask that data structure w/in your for/while loop whether to skip a given question if a previous question makes it irrelevant.

This would also allow you to skip a question but still go on to the next question

Something like:

data_definition = [
    {
        "key_name": "var1",
        "prompt": "Question 1:\n",
        "dependencies": None,
        "default_val": None,
    },
    {
        "key_name": "var2",
        "prompt": "Question 2:\n",
        "dependencies": None,
        "default_val": None,
    },
    {
        "key_name": "var3",
        "prompt": "Question 3:\n",
        "dependencies": None,
        "default_val": None,
    },
    {
        "key_name": "var4",
        "prompt": "Question 4:\n",
        "dependencies": {"var3": "no"},
        "default_val": None,
    },
]

input_dict = {}

for question in data_definition:
    # if any (could change this to all if you like) of the dependencies are satisfied, skip the question
    skip = False
    for dep, skip_answer in (question["dependencies"] or {}).items():
        if dep in input_dict and input_dict[dep] == skip_answer:
            input_dict[question["key_name"]] = question["default_val"]
            skip = True
            break
    if skip:
        continue

    input_dict[question["key_name"]] = input(question["prompt"])

Upvotes: 0

crayxt
crayxt

Reputation: 2405

This should be a simple example, assuming you are storing questions in plain text. We loop over sorted keys.

input_dict = {'var1': 'Question 1:',
              'var2': 'Question 2:',
              'var3': 'Question 3:',
              'var4': 'Question 4:'}

out_dict = {}

for q in sorted(input_dict.keys()):
    ans = input(input_dict[q])
    out_dict[q] = ans
    if ans == "no":
        break

Question 1:yes
Question 2:yes
Question 3:no
>>> out_dict
{'var1': 'yes', 'var2': 'yes', 'var3': 'no'}

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195553

You can create a for-loop and break if question number is 3 and answer is "no":

input_dict = {}
for question in range(1, 5):
    ans = input("Question {}:".format(question))
    input_dict["var{}".format(question)] = ans
    if question == 3 and ans == "no":
        break

print(input_dict)

Prints:

Question 1:yes
Question 2:yes
Question 3:no
{'var1': 'yes', 'var2': 'yes', 'var3': 'no'}

Upvotes: 2

Related Questions