Creating a multiple choice quiz in Python | Terminal

If you are a programmer wanting to learn Python, I suggest you start IMMEDIATELY. If you look at syntax for Python, it looks very user friendly and easy to work with, because IT IS. You are basically telling the computer what to do in broken English.

Creating a small terminal application can take no time if you understand the basics of Python. I’m gonna show you how you can create a multiple choice quiz app in your terminal.

I like to have my code broken up to where one file does one thing, but for the sake of this blog I’m going to keep my code in the same file. You will start out by creating your questions in a list and storing them in a variable like this:

You may notice a weird synax with in the prompts, \n. This is called an escape key. It is used for spacing purposes, \n is used to put whatever follows it on a new line.

If you think about a question for a quiz and how it is structured it has two key parts. The prompt, or the question that is asked, and the answer, so the best way to define a question would be with a class so you can give it those two attributes.

I created a question class that accepts two parameters, the question prompt and the correct answer. For each question_prompt I created an object of the question and stored it inside of another list variable called questions. Doing this allows me to have 3 separate question objects with prompts and correct answers for each question.

After creating that variable, I want to be able to loop through each question object inside of the questions variable. The easiest way to do this will to create a function that contains a for loop that loops through the questions list and accepts a list as a parameter.

In the for loop I set a variable named answer to the input that is given by the user, so I can later compare the users input to the correct answer. I also like to keep a score, so I can tell how many questions the user gets correct, so I set a variable named score set to 0.

To check the users input and set the score if they get it correct, I used an if conditional statement. I checked the users input against the answer attribute of the question being asked, and if they get the answer right I used a shorthand for score = score + 1.

At the end of the quiz, I want to print out how many questions the user got right. So I printed out the final score against the length of the questions list. That’s all it takes, you then call the run_quiz function at the end of the file and pass in the questions variable for your program to run.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store