Quiz application in python using database
In this tutorial, you’ll build a Python quiz application for the terminal. The word quiz was first used in 1781 to mean eccentric person. Nowadays, it’s mostly used to describe short tests of trivia or expert knowledge with questions like the following: Show
By following along in this step-by-step project, you’ll build an application that can test a person’s expertise on a range of topics. You can use this project to strengthen your own knowledge or to challenge your friends to a fun battle of wits. In this tutorial, you’ll learn how to:
The quiz application is a comprehensive project for anyone comfortable with the basics of Python. Throughout the tutorial, you’ll get all the code you need in separate, bite-size steps. You can also find the full source code of the application by clicking on the link below: Whether you’re an eccentric person or not, read on to learn how to create your own quiz. Demo: Your Python Quiz ApplicationIn this step-by-step project, you’ll build a terminal application that can quiz you and your friends on a range of topics:
You first choose a topic for your questions. Then, for each question, you’ll choose an answer from a set of alternatives. Some questions may have multiple correct answers. You can access a hint to help you along the way. After answering a question, you’ll read an explanation that can provide more context for the answer. Project OverviewYou’ll start by creating a basic Python quiz application that’s only capable of asking a question, collecting an answer, and checking whether the answer is correct. From there, you’ll add more and more features in order to make your app more interesting, user-friendly, and fun. You’ll build the quiz application iteratively by going through the following steps:
As you follow along, you’ll gain experience in starting with a small script and expanding it. This is an important skill in and of itself. Your favorite program, app, or game probably started as a small proof of concept that later grew into what it is today. PrerequisitesIn this tutorial, you’ll build a quiz application using Python’s basic building blocks. While working through the steps, it’s helpful if you’re comfortable with the following concepts:
If you’re not confident in your knowledge of these prerequisites, then that’s okay too! In fact, going through this tutorial will help you practice these concepts. You can always stop and review the resources linked above if you get stuck. Step 1: Ask QuestionsIn this step, you’ll learn how to create a program that can ask questions and check answers. This will be the foundation of your quiz application, which you’ll improve upon in the rest of the tutorial. At the end of this step, your program will look like this:
Your program will be able to ask questions and check answers. This version includes the basic functionality that you need, but you’ll add more functionality in later steps. If you prefer, then you can download the source code as it’ll look when you’re done with this step by clicking the link below and entering the Get User Information With input()One of Python’s built-in functions is >>>
You can use >>>
This example shows one thing that you need to be aware of: Time to start building your quiz application. Open your editor and create the file
This code is very similar to what you experimented with in the REPL above. You can run your application to check your knowledge:
If you happen to give the wrong answer, then you’ll be gently corrected so that you’ll hopefully do better next time. A quiz with only one question isn’t very exciting! You can ask another question by repeating your code:
You’ve added a question by copying and pasting the previous code then changing the question text and the correct answer. Again, you can test this by running the script:
It works! However, copying and pasting code like this isn’t great. There’s a programming principle called Don’t Repeat Yourself (DRY), which says that you should usually avoid repeated code because it gets hard to maintain. Next, you’ll start improving your code to make it easier to work with. Use Lists and Tuples to Avoid Repetitive CodePython provides several flexible and powerful data structures. You can usually replace repeated code with a
tuple, a list, or a dictionary in combination with a Instead of repeating code, you’ll treat your questions and answers as data and move them into a data structure that your code can loop over. The immediate—and often challenging—question then becomes how you should structure your data. There’s never one uniquely perfect data structure. You’ll usually choose between several alternatives. Throughout this tutorial, you’ll revisit your choice of data structure several times as your application grows. For now, choose a fairly simple data structure:
You can then store your questions as follows:
This fits nicely with how you want to use your data. You’ll loop over each question, and for each question, you want access to both the question and answer. Change your
When you run this code, it shouldn’t look any different from how it did earlier. In fact, you haven’t added any new functionality. Instead, you’ve refactored your code so that it’ll be easier to add more questions to your application. In the previous version of your code, you needed to add five new lines of code for each question that you added. Now, the Next, you’ll make your quiz application easier to use by adding answer alternatives for each question. Provide Multiple ChoicesUsing
Should they really be marked wrong because they included the parentheses to indicate that the function is callable? You can take away a lot of guesswork for the users by giving them alternatives. For example:
Here, the alternatives show that you expect the answer to be entered without parentheses. In the example, the alternatives are listed before the question. This is a bit counterintuitive, but it’s easier to implement into your current code. You’ll improve this in the next step. In order to implement answer alternatives, you need your data structure to be able to record three pieces of information for each question:
It’s time to revisit You decide to change You update your code to loop over each item in your newly minted dictionary. For each question, you pick out the correct answer from the alternatives, and you print out all the alternatives before asking the question:
If you always showed the correct answer as the first alternative, then your users would soon catch on and be able to guess the correct answer every time. Instead, you change the order of the alternatives by sorting them. Test your application:
The last question reveals another experience that can be frustrating for the user. In this example, they’ve chosen the correct alternative. However, as they were typing it, a typo snuck in. Can you make your application more forgiving? You know that the user will answer with one of the alternatives, so you just need a way for them to communicate which alternative they choose. You can add a label to each alternative and only ask the user to enter the label. Update the application to use
You store the reordered alternatives as Now, it’s more convenient to answer the questions:
Great! You’ve created quite a capable quiz application! In the next step, you won’t add any more functionality. Instead, you’ll make your application more user-friendly. Step 2: Make Your Application User-FriendlyIn this second step, you’ll improve on your quiz application to make it easier to use. In particular, you’ll improve the following:
At the end of this step, your application will work as follows:
Your program will still work similarly to now, but it’ll be more robust and attractive. You can find
the source code as it’ll look at the end of this step in the Format the Output More NicelyLook back at how your quiz application is currently presented. It’s not very
attractive. There are no blank lines that tell you where a new question starts, and the alternatives are listed above the question, which is a bit confusing. Furthermore, the numbering of the different choices start at In your next update to
You use >>>
You use these labeled alternatives when you display the options to the user and when you look up the user’s answer based on the label that they entered. Note the use of the special escape string
Your output is still mostly monochrome in the terminal, but it’s more visually pleasing, and it’s easier to read. Keep ScoreNow that you’re numbering the questions, it would also be nice to
keep track of how many questions the user answers correctly. You can add a variable,
You increase Handle User ErrorsSo far, you haven’t worried too much about what happens if the user enters an answer that’s not valid. In the different versions of your app, this oversight could result in the program raising an error or—less dramatically—registering a user’s invalid answer as wrong. You can handle user errors in a better way by allowing the user to re-enter their answer when they enter something invalid. One way to do this is
to wrap >>>
The condition In your quiz application, you use a similar construct to loop until the user gives a valid answer:
If you enter an invalid choice at the prompt, then you’ll be reminded about your valid choices:
Note that once the Add Variety to Your QuizCurrently, when you run your quiz application, you’re always asking the questions in the same order as they’re listed in your source code. Additionally, the answer alternatives for a given question also come in a fixed order that never changes. You can add some variety to your quiz by changing things up a little. You can randomize both the order of the questions and the order of the answer alternatives for each question:
You use >>>
Additionally, you cap the number of questions in the quiz to
Throughout this step, you’ve improved on your quiz application. It’s now time to take a step back and consider the code itself. In the next section, you’ll reorganize the code so that you keep it modular and ready for further development. Step 3: Organize Your Code With FunctionsIn this step, you’ll refactor your code. Refactoring means that you’ll change your code, but your application’s behavior and your user’s experience will stay as they are. This may not sound very exciting, but it’ll be tremendously useful down the line, as good refactorings make it more convenient to maintain and expand your code. Currently, your code isn’t particularly organized. All your statements are fairly low level. You’ll define functions to improve your code. A few of their advantages are the following:
To see how the code will look after you’ve refactored it, click below and check out the Prepare DataMany games and applications follow a common life cycle:
In your quiz application, you first read the available questions, then you ask each of the questions, before finally reporting the final score. If you look back at your current code, then you’ll see these three steps in the code. But the organization is still a bit hidden within all the details. You can make the main functionality clearer
by encapsulating it in a function. You don’t need to update your
This code won’t run as it is. The functions Writing down your application flow at a high level like this can be a great start to uncover which functions are natural building blocks in your code. In the rest of this section, you’ll fill in the missing details:
You’re now going to make quite substantial changes to the code of your quiz application as you’re refactoring it to use functions. Before doing so, it’s a good idea to make sure you can revert to the current state, which you know works. You can do this either by saving a copy of your code with a different filename or by making a commit if you’re using a version control system. Once you’ve safely stored your current code, start with a new
Remember that you’re only reorganizing your code. You’re not adding new functionality, so you won’t need to import any new libraries. Next, you’ll implement the necessary preprocessing. In this case, this means that you’ll prepare the
Note that Ask QuestionsLook back on your sketch for
the Think about what
These are a lot of small things to do in one function, and you could consider whether there’s potential for further modularization. For example, items 3 to 6 in the list above are all about interacting with the user, and you can pull them into yet another helper function. To achieve this modularization, add the following
This function accepts a question text and a list of alternatives. You then use the same techniques as earlier to label the alternatives and ask the user to enter a valid label. Finally, you return the user’s answer. Using
You first randomly reorder the answer alternatives using You’re now ready to implement
As earlier,
you use Your refactoring is now complete, except for one thing. If you run
You call That’s it! You’ve refactored your code into several functions. This will help you in keeping track of the functionality of your application. It’ll also be useful in this tutorial, as you can consider changes to individual functions instead of changing the whole script. For the rest of the tutorial, you’ll see your full code listed in collapsible boxes like the one below. Expand these to see the current state and get an overview of your full application: The full source code of your quiz application is listed below:
Run your application with Through this step, you’ve refactored your code to make it more convenient to work with. You separated your commands into well-organized functions that you can continue to develop. In the next step, you’ll take advantage of this by improving how you read questions into your application. Step 4: Separate Data Into Its Own FileYou’ll continue your refactoring journey in this step. Your focus will now be how you provide questions to your application. So far, you’ve stored the questions directly in your
source code in the In this section, you’ll learn how to store your questions in a separate data file formatted according to the TOML standard. Other options—that you won’t cover in this tutorial—are storing the questions in a different file format like JSON or YAML, or storing them in a database, either a traditional relational one or a NoSQL database. To peek at how you’ll improve your
code in this step, click below and go to the Move Questions to a TOML FileTOML is branded as “a config file format for humans” (Source). It’s designed to be readable by humans and uncomplicated to parse by computers. Information is represented in key-value pairs that can be mapped to a hash table data structure, like a Python dictionary. TOML supports several data types, including strings, integers, floating-point numbers, Booleans, and dates. Additionally, data can be structured in arrays and tables, which are similar to Python’s lists and dictionaries, respectively. TOML has been gaining popularity over the last years, and the format is stable after version 1.0.0 of the format specification was released in January 2021. Create a new text file that you’ll call
While there are differences between TOML syntax and Python syntax, you’ll recognize elements like using quotation marks ( To work with TOML files in Python, you need a library that parses them. In this tutorial, you’ll use Before installing
You can then install
You can check that you have >>>
First, observe that You can use You can integrate the TOML file into your quiz application by updating the preamble of your code, where you do your imports and define the global variables:
Instead of doing a plain You’re using Finally, you use Go ahead and add a few more questions to your TOML file to confirm that it’s being used. Add Flexibility to Your Data FormatYou’ve moved your question data out of your source code and into a dedicated data file format. One advantage of TOML over a regular Python dictionary is that you can add some more structure to your data while keeping it fairly readable and maintainable. One notable feature of TOML is tables. These are named sections that map to nested dictionaries in Python. Furthermore, you can use arrays of tables, which are represented by lists of dictionaries in Python. You can take advantage of these to be more explicit when defining your questions. Consider the following TOML snippet:
Regular tables start with a single-bracketed line like >>>
This results in a nested data structure, with an outer dictionary in which the This structure is a bit more complicated than what you’ve used so far. However, it’s also more explicit, and you don’t need to rely on conventions such as the first answer alternative representing the correct answer. You’ll now convert your quiz application so that it takes advantage of this new data structure for your questions. First, reformat your questions in
Each question is stored inside an individual
Principally, you’ll need to make two changes to your application source code to use the new format:
These changes touch on your main data structure, so they require several small code changes throughout your code. First, change how you read the questions from the TOML file:
You change This latter point requires some changes in
You now pick out the question text, the correct answer,
and the answer alternatives explicitly from the new You don’t need to make any changes in You can find the current, full source code of your application inside the collapsed sections below: The full
Save this file in the same folder as The full source code of your quiz application is listed below:
Run your application with Your new flexible format for defining questions gives you some options in adding more functionality to your quiz application. You’ll dive into some of these in the next step. Step 5: Expand Your Quiz FunctionalityIn this fifth step, you’ll add more functionality to your quiz application. Finally, the refactoring you’ve done in the previous steps will pay off! You’ll add the following features:
At the end of this step, your application will work as follows:
These new features provide a more interesting experience to anyone challenging
themselves through your quiz application. You can see how the source code of your application will look when you’re done with this step by clicking below and moving into the Allow Multiple Correct AnswersSome questions may have multiple correct answers, and it’ll be great if your quiz can handle those as well. In this section, you’ll add support for multiple correct answers. First, you need to consider how you can represent several correct answers in your Your questions file will then look something like the following:
For old questions with only one correct answer, there will be only one answer listed in the Once your data structure is updated, you’ll need to implement the feature in your code as well. You don’t need to make any changes in Start with the latter challenge. How can the user enter multiple answers, and how can you validate that each one is valid? One possibility is to enter multiple answers as a comma-separated string. You can then convert the string to a list as follows: >>>
You could use The test for valid answers becomes a bit more complicated, though. You therefore replace the tight
Before looking too closely at the details in the code, take the function for a test run: >>>
Your function first checks that the answer includes the appropriate number of choices. Then each one is checked to make sure it’s a valid choice. If any of these checks fail, then a helpful message is printed to the user. In the code, you also make some effort to handle the distinction between one and several items when it comes to grammar. You use Additionally, you convert the answers to a set to quickly ignore duplicate alternatives. An answer string like Finally, note that Next, you adapt Because the order of the answers is
irrelevant, you use
You only score a point for the user if they find all the correct answers. Otherwise, you list all correct answers. You can now run your Python quiz application again:
Allowing multiple correct answers gives you more flexibility in which kinds of questions you can ask in your quizzes. Add Hints to Help the UserSometimes when you’re asked a question, you need a bit of help to jog your memory. Giving the users the option of seeing a hint can make your quizzes more fun. In this section, you’ll extend your application to include hints. You can include hints in your
Each question in the TOML file is represented by a dictionary in Python. The new Instead, you adapt your code to take advantage of the new optional field. In
You use Again, you’ll make bigger changes to
If a hint is provided, then it’s added to the end of
In the next section, you’ll add a similar feature. In addition to showing an optional hint before the user answers a question, you’ll show an explanation after they’ve answered it. Add Explanations to Reinforce LearningYou can implement explanations similarly to how you implemented hints in the previous section. First, you’ll add an optional Start with adding
TOML supports multiline strings by using triple quotes ( The explanations will be printed to the screen after the user has answered a question. In other words, the explanations aren’t part of the user interaction done in
Because you print the explanation after giving the user feedback on whether their answer was correct or not, you can’t return inside the Your explanations look something like the following when you run your quiz application:
The improvements to your Python quiz application add up. Feel free to expand the collapsed sections below to see the full source code with all your new features: The full
Save this file in the same folder as The full source code of your quiz application is listed below:
Run your application with
In the final step, you’ll add one more feature: support for several quiz topics within your application. Step 6: Support Several Quiz TopicsIn this section, you’ll make one final improvement that will make your Python quiz application more fun, varied, and interesting. You’ll add the option of grouping questions into different topics and letting your users pick which topic they’ll be quizzed about. The final version of your Python quiz application will look as follows:
More topics and new questions will keep your quiz application fresh. Click below and navigate to the
Sections in TOML files can be nested. You create nested tables by adding periods ( >>>
Here, the section header You can reorganize
Now, there are two topics included in the data file: Python and Capitals. Within each topic section, the question tables are still structured the same as before. This means that the only change you need to make is how you prepare the questions. You start by reading and parsing
The data structure returned by Run your Python quiz application. You’ll be greeted by the new topic prompt:
This ends the guided part of this journey. You’ve created a powerful Python quiz application in the terminal. You can see the complete source code as well as a list of questions by expanding the boxes below: The full
Save this file in the same folder as The full source code of your quiz application is listed here:
Run your application with You can also access the source code and the questions file by clicking below: You’ll find the final version of the application in the directory ConclusionGood job! You’ve created a flexible and useful quiz application with Python. Along the way, you’ve learned how you can start with a basic script and build it out to a more complex program. In this tutorial, you’ve learned how to:
Now, go have some fun with your quiz application. Add some questions on your own, and challenge your friends. Share your best questions and quiz topics in the comments below! Next StepsAs you’ve followed along in this tutorial, you’ve created a well-featured quiz application. However, there’s still ample opportunity to improve on the project. Here are some ideas for additional features:
You can also reuse the logic in this quiz application but change the front-end presentation layer. Maybe you can convert the project to a web application or create a flashcards app to help you prepare for your quizzes. Feel free to share your improvements in the comments below. How do you make a quiz application in Python?Build a Quiz Application With Python. Demo: Your Python Quiz Application.. Project Overview.. Prerequisites.. Step 1: Ask Questions. ... . Step 2: Make Your Application User-Friendly. ... . Step 3: Organize Your Code With Functions. ... . Step 4: Separate Data Into Its Own File. ... . Step 5: Expand Your Quiz Functionality.. How do you make a python GUI quiz?Importing the module: tkinter and json.. Create the main window (container) of the app.. Add widgets to display data.. Add the functionalities to the button.. Using the data in the Quiz.. What are some Python projects for beginners?Python Project Ideas: Beginner Level. Create a code generator. ... . Build a countdown calculator. ... . Write a sorting method. ... . Build an interactive quiz. ... . Tic-Tac-Toe by Text. ... . Make a temperature/measurement converter. ... . Build a counter app. ... . Build a number-guessing game.. How do you make a quiz app?7 steps to build a quiz game for Android. Open the Quiz App Template. Click on "Create App Now" button or visit AppsGeyser.com, open the "Quiz" app template.. Set Up Categories. ... . Add Questions & Answers. ... . Customize App Design. ... . Name your App. ... . Submit an Icon. ... . Publish App on Google Play. |