Home > Net >  Taking, storing, and returning multiple inputs Python
Taking, storing, and returning multiple inputs Python

Time:11-06

I am trying to make a program that lets a user input a question and answer and then prompts these questions and returns whether the answer is correct. I am guessing that I have to create functions that take input and store them in lists and then return them.

I am having troubling figuring out how to retrieve the items in lists together. I can obviously write out code for each question and answer, but I am sure that is not good code and is impractical if more items are added. What would be the best way to do this? I am thinking to create two lists and loop through them both when prompted, but I am struggling to figure the syntax out (or if there is a better way?).

Here is what I have so far, but I know it's wrong. Cheers.

question_list = ['What is the capital of Japan?: ', 'What is capital of US?: ']
answer_list = ['Tokyo', 'Washington DC']

def return_question():
    for question in question_list:
        input_answer = input(question).lower()
        for answer in answer_list:
            if input == answer_list:
                print('Correct')
            else:
                print('Incorrect')

CodePudding user response:

Use zip to iterate through paired questions and answers.

>>> question_list = ['What is the capital of Japan?: ', 'What is capital of US?: ']
>>> answer_list = ['Tokyo', 'Washington DC']
>>> def ask_questions():
...     for q, a in zip(question_list, answer_list):
...         answer = input(q)
...         if a.lower() == answer.lower():
...             print('Correct')
...         else:
...             print('Incorrect')
...
>>> ask_questions()
What is the capital of Japan?: TOKYO
Correct
What is capital of US?: BRANSON
Incorrect

CodePudding user response:

I fully agree with the answer given by @GreenCloakGuy above. But even more Pythonic would be:

questions_and_answers = [
    ('What is the capital of Japan?', 'Tokyo'),
    ('What is the capital of the USA?', 'Washington DC'),
]

for question, answer in questions_and_answers:
    ...

Why do you want the questions and answers in separate lists? You are guaranteeing that at sometime in the future, someone will make an editing error and the two lists will get out of sync. What you have is a list of questions and answers, not a list of questions and a separate list of answers.

  • Related