Building a Small Project: Quiz Game
Put variables, loops, conditions and functions together to build a real game
- ask a question and check the answer with
input()andif, - keep a running score in a variable,
- wrap the "ask one question" idea in a function that returns points,
- use a
forloop and a list to run the whole quiz.
1. The plan: input -> process -> output
A quiz game is just a loop of a very simple idea. For each question the computer does three things: ask (show the question and read your answer), check (is the answer correct?), and update (add a point if it was right). After all the questions, it shows your final score.
Think of a friendly game-show host with a stack of cards. They read a card, listen to your answer, tick a box if you are right, then reach for the next card. When the cards run out, they announce your score. Our program is that host.
2. Step 1: one question with input and if
Let us start with the smallest possible quiz: a single question. input() shows a message and waits for the person to type. It always hands back what they typed as text (a string). We then compare that text with the correct answer using ==.
answer = input("What is 2 + 2? ")
if answer == "4":
print("Correct!")
else:
print("Wrong.")
Sample run (the person types 4):
What is 2 + 2? 4
Correct!
Because input() gives back text, we compare with the text "4" in quotes, not the number 4. The if line ends with a colon, and the lines that belong to it are indented.