Project: Terminal Quiz Game
In this project you will build a complete quiz game that runs in the terminal. It asks five general knowledge questions, accepts answers in any capital letters and with extra spaces, gives a second chance with fewer points, tracks your best streak, lets you quit at any time, and shows a results screen with a grade. Then it asks if you want to play again.
Everything uses skills from Level 1 only: variables, input() and print(), strings and string methods, if/elif/else, for and while loops, range(), break, continue, loop else and the loop recipes. If any step feels unfamiliar, the link next to it takes you back to the lesson that explains it.
What we are building
Here is the plan, written as a list of features before any code. Professionals do this too: it is much easier to build a program when you know what "finished" looks like.
- Store five questions and their correct answers.
- Check an answer fairly: ignore capital letters and extra spaces, and accept more than one correct spelling.
- Ask every question and keep a score.
- Give a second try: 10 points on the first try, 5 on the second.
- Track the longest run of correct answers (the streak), and let the player type
quit. - Show a results screen with a percentage, stars and a grade.
- Ask the player's name and offer to play again.
A note about input on this page. The runnable editor on this site can only use input() in the Input & Output lesson. So in Steps 1 to 5 a list called typed stands in for what the player types. Each time the game needs an answer, it takes the next item from that list. In Step 6 you will swap that one line for input() and play it for real in your terminal.
Step 1: store the questions
We need two lists that line up: question 1 goes with answer 1, and so on. Some questions have more than one acceptable answer (11 or eleven), so those answers are stored in one string separated by a | character. Store them in small letters, because we will compare small letters later.
questions = [
"Which city is known as the Pink City?",
"How many players does a cricket team have on the field?",
"Which river flows through Varanasi?",
"What is 15% of 200?",
"Which planet is called the Red Planet?",
]
answers = ["jaipur", "11|eleven", "ganga|ganges", "30", "mars"]
print("Questions loaded:", len(questions))
number = 0
for question, accepted in zip(questions, answers, strict=True):
number += 1
print(f"Q{number}. {question} -> {accepted}")Questions loaded: 5 Q1. Which city is known as the Pink City? -> jaipur Q2. How many players does a cricket team have on the field? -> 11|eleven Q3. Which river flows through Varanasi? -> ganga|ganges Q4. What is 15% of 200? -> 30 Q5. Which planet is called the Red Planet? -> mars
zip() with strict=True from for Loops walks both lists together and raises an error if you forget an answer, so a mismatch is caught at once. number is a counter from Loop Recipes. You will learn lists properly in Lists; for now you only need to loop over them.
Step 2: check an answer fairly
A player who types JAIPUR deserves the marks. Two string methods from String Methods make the check fair: strip() removes spaces at the ends and lower() turns everything into small letters. Then split("|") turns "ganga|ganges" into a list of accepted answers, and in checks whether the reply is one of them.
accepted = "ganga|ganges"
tries = ["Ganga", " GANGES ", "Yamuna", "gang a", ""]
for raw in tries:
reply = raw.strip().lower()
if reply in accepted.split("|"):
print(f"{raw!r:12} -> correct")
else:
print(f"{raw!r:12} -> wrong")'Ganga' -> correct ' GANGES ' -> correct 'Yamuna' -> wrong 'gang a' -> wrong '' -> wrong
!r shows each raw reply with its quotes, so you can see the spaces, and :12 pads it to a column. Notice that a space inside the word still makes it wrong. That is fair: the player typed a different word.
Why not write if reply in accepted: on the whole string? Because in on a string searches for any piece of text, so "gang" would be found inside "ganga|ganges" and marked correct. Splitting first makes in compare whole answers.
Step 3: ask every question and keep score
Now put Steps 1 and 2 together in one loop. The list typed holds the player's replies, and the counter turn points at the next one to use.
questions = [
"Which city is known as the Pink City?",
"How many players does a cricket team have on the field?",
"Which river flows through Varanasi?",
"What is 15% of 200?",
"Which planet is called the Red Planet?",
]
answers = ["jaipur", "11|eleven", "ganga|ganges", "30", "mars"]
typed = [" JAIPUR ", "eleven", "Yamuna", "30", "pluto"]
turn = 0
score = 0
for question, accepted in zip(questions, answers, strict=True):
print(question)
reply = typed[turn].strip().lower()
turn += 1
if reply in accepted.split("|"):
score += 1
print(" Correct!")
else:
print(" Wrong.")
print(f"You scored {score} out of {len(questions)}")Which city is known as the Pink City? Correct! How many players does a cricket team have on the field? Correct! Which river flows through Varanasi? Wrong. What is 15% of 200? Correct! Which planet is called the Red Planet? Wrong. You scored 3 out of 5
This is already a working quiz. score is a counter that only grows when the if is true. Change the items in typed and run it again to check that the score follows.
Step 4: a second chance
A good quiz is forgiving. If the first answer is wrong, the player gets one more try for half the points. That means a small loop inside the question loop: a nested loop, as in Nested Loops & Patterns.
The inner loop runs at most MAX_TRIES times. A correct answer ends it early with break. If both tries are wrong, the loop ends without break, so its else block runs and shows the right answer. This is the retry pattern from break, continue & Loop else.
questions = [
"Which city is known as the Pink City?",
"How many players does a cricket team have on the field?",
"Which river flows through Varanasi?",
]
answers = ["jaipur", "11|eleven", "ganga|ganges"]
MAX_TRIES = 2
typed = ["jaipur", "12", "eleven", "yamuna", "godavari"]
turn = 0
score = 0
for question, accepted in zip(questions, answers, strict=True):
print(question)
for attempt in range(1, MAX_TRIES + 1):
reply = typed[turn].strip().lower()
turn += 1
if reply in accepted.split("|"):
points = 10 if attempt == 1 else 5
score += points
print(f" Correct! +{points} points")
break
if attempt < MAX_TRIES:
print(" Not quite. One more try.")
else:
first_answer = accepted.split("|")[0]
print(f" Sorry, the answer is {first_answer.title()}.")
print("Score:", score)Which city is known as the Pink City? Correct! +10 points How many players does a cricket team have on the field? Not quite. One more try. Correct! +5 points Which river flows through Varanasi? Not quite. One more try. Sorry, the answer is Ganga. Score: 15
Three details are worth a closer look:
range(1, MAX_TRIES + 1)numbers the tries 1 and 2, soattempt == 1reads naturally.10 if attempt == 1 else 5is a conditional expression from if, elif & else.- "One more try" is printed only when a try is left. On the last wrong try the loop ends, and
elsespeaks instead.
MAX_TRIES is written in capitals to show it is a constant: a setting you choose once and do not change while the program runs. Change it to 3 and the whole game gives three tries.
Step 5: streaks, quitting and the results screen
Now the finishing touches, each one a recipe you already know:
- Streak:
streakcounts correct answers in a row and goes back to 0 after a miss.best_streakis a running maximum of it. - Quit: typing
quitmust stop both loops.breakonly leaves the inner loop, so we set a flag,quit_game, and check it in the outer loop. - Results: a percentage, a line of stars made with string repetition (
"*" * 4is"****"), and a grade from anelifchain with the strictest test first.
questions = [
"Which city is known as the Pink City?",
"How many players does a cricket team have on the field?",
"Which river flows through Varanasi?",
"What is 15% of 200?",
"Which planet is called the Red Planet?",
]
answers = ["jaipur", "11|eleven", "ganga|ganges", "30", "mars"]
MAX_TRIES = 2
typed = ["Jaipur", "12", "eleven", "Ganga", "25", "20", "MARS"]
turn = 0
score = 0
correct = 0
answered = 0
streak = 0
best_streak = 0
quit_game = False
for question, accepted in zip(questions, answers, strict=True):
print(f"Q{answered + 1}. {question}")
for attempt in range(1, MAX_TRIES + 1):
reply = typed[turn].strip().lower()
turn += 1
if reply == "quit":
quit_game = True
break
if reply in accepted.split("|"):
points = 10 if attempt == 1 else 5
score += points
correct += 1
streak += 1
if streak > best_streak:
best_streak = streak
print(f" Correct! +{points} points")
break
if attempt < MAX_TRIES:
print(" Not quite. One more try.")
else:
first_answer = accepted.split("|")[0]
print(f" Sorry, the answer is {first_answer.title()}.")
streak = 0
if quit_game:
break
answered += 1
print("-" * 30)
if answered == 0:
print("No questions answered this time.")
else:
best_possible = answered * 10
percent = score / best_possible * 100
if percent >= 90:
verdict = "Quiz champion!"
elif percent >= 60:
verdict = "Well played!"
elif percent >= 40:
verdict = "Good effort."
else:
verdict = "Keep practising."
print(f"{correct} of {answered} correct")
print(f"Score: {score}/{best_possible} ({percent:.0f}%)")
print("Stars:", "*" * correct)
print("Best streak:", best_streak)
print(verdict)Q1. Which city is known as the Pink City? Correct! +10 points Q2. How many players does a cricket team have on the field? Not quite. One more try. Correct! +5 points Q3. Which river flows through Varanasi? Correct! +10 points Q4. What is 15% of 200? Not quite. One more try. Sorry, the answer is 30. Q5. Which planet is called the Red Planet? Correct! +10 points ------------------------------ 4 of 5 correct Score: 35/50 (70%) Stars: **** Best streak: 3 Well played!
Trace the streak: Q1, Q2 and Q3 are correct (streak 3), Q4 is missed (streak back to 0), Q5 is correct (streak 1). The best was 3.
Notice the order at the bottom of the question loop. The quit check comes before answered += 1, so a question the player walked away from is not counted. And the answered == 0 guard protects the percentage from dividing by zero if the player quits on question 1. Try it: put "quit" as the first item in typed and run again.
Step 6: play it for real
Save the final program below as quiz.py. It makes three changes to Step 5:
- The line
reply = typed[turn].strip().lower()becomesreply = input("Your answer: ").strip().lower(), and thetypedandturnlines are gone. - The game asks for the player's name first. An empty name becomes
"Player", because an empty string is falsy. - The whole game sits inside a
while True:loop. At the end it asks "Play again?" andbreaks unless the answer isyoryes. The score variables are set to 0 inside this loop, so each new game starts fresh.
# quiz.py: a terminal quiz game built with Level 1 Python
questions = [
"Which city is known as the Pink City?",
"How many players does a cricket team have on the field?",
"Which river flows through Varanasi?",
"What is 15% of 200?",
"Which planet is called the Red Planet?",
]
answers = ["jaipur", "11|eleven", "ganga|ganges", "30", "mars"]
MAX_TRIES = 2
print("=" * 40)
print("DESI QUIZ: 5 questions")
print("10 points on the first try, 5 on the second")
print("Type 'quit' to stop early")
print("=" * 40)
player = input("Your name: ").strip().title()
if not player:
player = "Player"
while True:
score = 0
correct = 0
answered = 0
streak = 0
best_streak = 0
quit_game = False
for question, accepted in zip(questions, answers, strict=True):
print()
print(f"Q{answered + 1}. {question}")
for attempt in range(1, MAX_TRIES + 1):
reply = input("Your answer: ").strip().lower()
if reply == "quit":
quit_game = True
break
if reply in accepted.split("|"):
points = 10 if attempt == 1 else 5
score += points
correct += 1
streak += 1
if streak > best_streak:
best_streak = streak
print(f"Correct! +{points} points")
break
if attempt < MAX_TRIES:
print("Not quite. One more try.")
else:
first_answer = accepted.split("|")[0]
print(f"Sorry, the answer is {first_answer.title()}.")
streak = 0
if quit_game:
break
answered += 1
print()
print("-" * 40)
if answered == 0:
print("No questions answered this time.")
else:
best_possible = answered * 10
percent = score / best_possible * 100
if percent >= 90:
verdict = "Quiz champion!"
elif percent >= 60:
verdict = "Well played!"
elif percent >= 40:
verdict = "Good effort."
else:
verdict = "Keep practising."
print(f"{player}: {correct} of {answered} correct")
print(f"Score: {score}/{best_possible} ({percent:.0f}%)")
print("Stars:", "*" * correct)
print("Best streak:", best_streak)
print(verdict)
print("-" * 40)
again = input("Play again? (yes/no): ").strip().lower()
if again not in ("y", "yes"):
break
print(f"Thanks for playing, {player}!")Run it with python quiz.py. Here is a real session: Aarav plays one full game, starts a second one and types quit on question 2. The text after each prompt is what he typed.
C:\Users\meera\python-practice> python quiz.py
========================================
DESI QUIZ: 5 questions
10 points on the first try, 5 on the second
Type 'quit' to stop early
========================================
Your name: aarav
Q1. Which city is known as the Pink City?
Your answer: Jaipur
Correct! +10 points
Q2. How many players does a cricket team have on the field?
Your answer: 12
Not quite. One more try.
Your answer: eleven
Correct! +5 points
Q3. Which river flows through Varanasi?
Your answer: Ganga
Correct! +10 points
Q4. What is 15% of 200?
Your answer: 25
Not quite. One more try.
Your answer: 20
Sorry, the answer is 30.
Q5. Which planet is called the Red Planet?
Your answer: MARS
Correct! +10 points
----------------------------------------
Aarav: 4 of 5 correct
Score: 35/50 (70%)
Stars: ****
Best streak: 3
Well played!
----------------------------------------
Play again? (yes/no): yes
Q1. Which city is known as the Pink City?
Your answer: jaipur
Correct! +10 points
Q2. How many players does a cricket team have on the field?
Your answer: quit
----------------------------------------
Aarav: 1 of 1 correct
Score: 10/10 (100%)
Stars: *
Best streak: 1
Quiz champion!
----------------------------------------
Play again? (yes/no): no
Thanks for playing, Aarav!title() turned the name aarav into Aarav. In the second game only one question was answered, so the score is out of 10, not 50.
Test it like a tester
Before you call a program finished, try the inputs that real players will type. Run quiz.py and check each row:
| Type this | You should see |
|---|---|
jAiPuR for Q1 | Correct! +10 points |
11 or eleven for Q2 | Correct |
| Nothing (just press Enter) | Counts as a wrong try |
quit on Q1 | "No questions answered this time." |
| Your name left empty | "Thanks for playing, Player!" |
YES at "Play again?" | A new game starts with score 0 |
If a row does not match, read the code for that feature again, or add a print() to see the value of a variable at that moment.
Common mistakes
- Setting the score to 0 outside the play-again loop. The second game then starts with the first game's points.
- Checking
reply in acceptedwithoutsplit(). Part of a word, such as"gang", would count as correct. - Forgetting the quit flag.
breakin the inner loop only ends that question; the next question appears anyway. - Lining up
elsewith theifinstead of the innerfor. The right answer is then shown after every wrong try. - Dividing by
answeredwithout a guard. Quitting on question 1 would crash withZeroDivisionError.
Interview questions
1. How would you make answer checking forgiving without accepting wrong answers?
Normalise the reply with strip() and lower(), store the accepted answers in the same form, and compare whole answers, for example by splitting a list of alternatives and using in on that list. Checking in on one long string would accept partial words.
2. Why is for-else a good fit for "two tries per question"?
for attempt in range(1, 3) limits the tries, break leaves as soon as the answer is right, and the else block runs only when every try was used without a break. That is exactly the moment to reveal the answer, with no extra flag.
3. How do you stop a game from inside a nested loop?
break leaves only the inner loop, so set a flag such as quit_game = True before breaking, and check it right after the inner loop to break the outer one too. Later you would put the game in a function and use return.
4. How can you test a program that reads from input()?
Separate where the answers come from and what the program does with them. Here a list of scripted replies replaced input() for testing. In larger projects, test tools such as pytest's monkeypatch can replace input() automatically, as you will see in the testing lessons.
Key points
- Plan features as a numbered list before writing code, then build and run one step at a time.
strip()andlower()make comparisons fair;split("|")withinaccepts several whole answers.- A nested
forwithrange(),breakandelsegives each question a limited number of tries. - Counters, totals, a running maximum and flags handle score, streak and quitting.
- A flag checked after the inner loop stops both loops; a guard prevents dividing by zero.
- A list of scripted replies lets you test the game without typing;
input()is a one-line swap.
Exercise
Add a skip command to the Step 5 game. When the player types skip, the game prints Skipped., moves straight to the next question without using the second try, gives no points and resets the streak. Count the skips and show Skipped: N on the results screen. Test it with typed = ["jaipur", "skip", "ganga", "skip", "mars"].
Show solution
Add a counter skipped = 0 next to the other score variables, and this check straight after the quit check inside the attempt loop:
if reply == "skip":
skipped += 1
streak = 0
print(" Skipped.")
breakThen add print("Skipped:", skipped) to the results screen, just before the verdict. With the test replies, the game prints:
Q1. Which city is known as the Pink City?
Correct! +10 points
Q2. How many players does a cricket team have on the field?
Skipped.
Q3. Which river flows through Varanasi?
Correct! +10 points
Q4. What is 15% of 200?
Skipped.
Q5. Which planet is called the Red Planet?
Correct! +10 points
------------------------------
3 of 5 correct
Score: 30/50 (60%)
Stars: ***
Best streak: 1
Skipped: 2
Well played!break leaves the attempt loop, so the second try is not used, and because the loop ended with break its else does not reveal the answer. A skipped question still counts as answered, so the score is out of 50.
Quick Quiz
1. Why does the game store answers like "ganga|ganges" and use split("|")?
split("|") gives a list of whole answers, so in checks for an exact match with any of them.
2. In the attempt loop, when does the else block that reveals the answer run?
A loop's else runs when the loop ends without break; a correct answer or quit both break out.
3. What would happen if score = 0 were placed before while True: instead of inside it?
The play-again loop would not reset the score, so points would carry over.
4. Why is answered += 1 placed after the if quit_game: break check?
If the player quits, break runs first and the unanswered question is not added to the count.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
