Raven wants a quiz to help new crew members learn Python. She has four questions written on cards, and she always shuffles the cards before each practice round.
"If the order never changes," she says, "people remember the order, not the answers."
Rocket picks up the stack of cards. "What do you notice?" Raven asks him, for once. He thinks. "Each card has two parts: a question and its answer. They have to stay together."
Nova draws each card as a pair of linked boxes. "I found a pattern," she says. "Python can keep two values together in round brackets. Shuffle the pairs and the answers travel with their questions."
Rocket starts typing the first pair.
A tuple is like a list in round brackets: ("What is 2 + 2?", "4"). Once made, it cannot be changed. Tuples are handy for small groups of values that belong together.
In a for loop, you can unpack a pair into two names at once: for question, answer in questions:. Each time round, question gets the first value and answer the second.
# python_quiz.py
import random
questions = [
("What does 7 // 2 give?", "3"),
("What type does input() give back?", "str"),
("What is the index of the first item in a list?", "0"),
("Which word leaves a loop early?", "break"),
]
random.shuffle(questions)
score = 0
for question, answer in questions:
reply = input(question + " ").strip().lower()
if reply == answer:
print("Correct!")
score = score + 1
else:
print("Not quite. The answer is", answer)
print(f"You scored {score} out of {len(questions)}.") Here is one run. Your questions will come in a shuffled order, so yours may look different:
What does 7 // 2 give? 3 Correct! What type does input() give back? int Not quite. The answer is str What is the index of the first item in a list? 0 Correct! Which word leaves a loop early? BREAK Correct! You scored 3 out of 4.
You can read a tuple item by index, just like a list. You can also unpack a tuple into separate names in one line.
Trying to change an item in a tuple gives a TypeError, because tuples cannot be changed.
>>> planet = ("Mars", 4)
>>> planet[0]
'Mars'
>>> name, order = planet
>>> order
4
>>> planet[1] = 5
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment | Statement | True or false? |
|---|---|
| A tuple is written in round brackets. | ? |
| You can append to a tuple. | ? |
| for q, a in questions unpacks each pair. | ? |
| Shuffling a list of tuples splits questions from answers. | ? |
Your quiz mixes itself up every time it runs. Tomorrow you will switch from chance to calendars with the datetime module.