How To Code A Quiz App In Python
Find the source code for this project here
Step 1: Setting Up the Questions
First, gather your quiz questions and multiple-choice answers. In our example, we have three thrilling questions. But feel free to add as many as you like!
if __name__ == "__main__": questions = [ "What book holds the record for the fastest selling book in history?", "How old was Queen Elizabeth II when she was first crowned the Queen of England?", "Which blood type is a universal donor?" ] answers = [ "A. The Hunger Games \nB. Harry Potter and the Deathly Hallows \nC. To Kill A Mockingbird", "A. 27 \nB. 24 \nC. 31", "A. O negative \nB. B Positive \nC. AB" ]
Step 2: Set Correct Answers
For each question, we need to specify the correct answer. This helps our quiz app determine the player's score.
correctAnswers = [1, 1, 0]
In our example, 'A' is the correct answer for the first two questions, and 'C' is the correct answer for the last question. Adjust these based on your questions and answers.
Step 3: Initialize Player's Score
To keep track of how well our players are doing, we'll start their score at zero.
playerScore = 0
Step 4: Welcome Your Players
Let's start by welcoming our players to our amazing app :)
print("Welcome to the best quiz app ever :)")
Step 5: Ask Questions and Collect Answers
Now, it's time to engage your players with your awesome questions and answer choices. We'll use a loop to go through each question. The player gets to choose their answer (A, B, or C). We'll also make sure to validate their input.
for i in range(len(questions)): print("Question #", i + 1) print(questions[i]) print(answers[i]) userInput = input("Please answer the question ('A', 'B', 'C')> ").upper()
Step 6: Check Player's Answers
We'll check if the player's answer is correct and adjust their score accordingly.
if (userInput == 'A' and correctAnswers[i] == 0): playerScore += 1 elif (userInput == 'B' and correctAnswers[i] == 1): playerScore += 1 elif (userInput == 'C' and correctAnswers[i] == 2): playerScore += 1
Step 7: Wrap Up and Celebrate!
The quiz has ended! Let's congratulate the players on completing the quiz and reveal their scores with enthusiasm.
print("Quiz Completed :)") print("Your score is: {0}/{1}".format(playerScore, len(questions)))
….and there ya have it! Good job, you are done! :)