[AI Terms You Sort of Know <Python Absolute Beginner 73>] Random Quiz with dict × random!
Let's make a random quiz with dict × random! 🎲
Last time, we learned how to present quiz questions in order using a dictionary and a for loop.
This time, we will practice using the same dictionary data "randomly".
🔹 Sample Code
import random
quiz = {
"りんごの色は?": "赤",
"バナナの色は?": "黄",
"ぶどうの色は?": "紫"
}
question = random.choice(list(quiz.keys()))
print(question)
user = input("答えを入力してね:")
if user == quiz[question]:
print("正解!🎉")
else:
print(f"残念…正解は {quiz[question]} でした!")
🔹 Execution Example
ぶどうの色は?
→ 紫
正解!🎉
Next, when you run it again...
バナナの色は?
→ 黄
正解!🎉
The questions change every time! 🎲
🧩 Explanation of the Mechanism
import random Declaration to use random functions
quiz = {...} Set of questions and answers (dictionary)
quiz.keys() Extract only the "questions" from the dictionary list(quiz.keys()) Convert keys to a list (in a format usable by choice)
random.choice(...) Randomly pick one from them!
💡 Why is list(quiz.keys()) necessary?
random.choice() can be used with ordered data like "lists" or "tuples".
However, quiz.keys() is a slightly special form called a "dictionary view".
Therefore, you need to convert it to a list first before using it.
🪄 Summary
dict Data set (questions and answers) random.choice() Pick one randomly
input() Enter the answer
if statement Perform a check
✏️ A quick review
Python's random is perfect for learning how AI "chooses" things.
Let's let the computer experience a little bit of what humans call "mood" or "choice" 🍀
Example: 🎲 Treasure Chest of Fate: Getting a random item
【The Spell for This Time】
By using random.choice(dict.keys()), you can randomly pick one from the keys (names) in the dictionary.
📜 Story: The Mysterious Treasure Chest
An adventurer discovered an old treasure chest deep in the forest. It seems to contain some random item inside. What comes out depends on luck!
import random
# 宝箱の中身と出現確率(キーが出現するアイテム名、値がその重み)
treasure_loot = {
"伝説の剣": 1, # レアなアイテム
"普通の薬草": 10, # よく出るアイテム
"銀のコイン": 5,
"毒のキノコ": 2 # ハズレ枠
}
# 宝箱からランダムに取り出すためのキーのリストを作成
# .keys()でキーだけを取得し、リストに変換
loot_items = list(treasure_loot.keys())
# random.choice()で、キーの中から一つをランダムに選ぶ
gained_item = random.choice(loot_items)
print("▼ 宝箱を開ける…!")
print(f"『{gained_item}』を手に入れた!")
# 取得したアイテムを使って、その効果を辞書から取得して表示
# 宝箱の中身の辞書から、選ばれたアイテムの値(出現率ではない、別の情報と仮定)を取り出す
# ここでは、わかりやすさのため「効果」が別の辞書にあると仮定します
item_effects = {
"伝説の剣": "攻撃力が+50される",
"普通の薬草": "HPが10回復する",
"銀のコイン": "資金が10G増える",
"毒のキノコ": "HPが-5される"
}
# 取得したアイテム名を使って、その効果を辞書から取り出す
effect = item_effects.get(gained_item, "効果不明")
🗝️ Explanation of the Spell
list(treasure_loot.keys()): random.choice() can only pick elements from lists or tuples. Therefore, we first extract only the dictionary keys (item names) and convert them into a list.
random.choice(loot_items): From this list, one item name (key) is randomly selected and assigned to gained_item.
item_effects.get(gained_item, "Unknown effect"): Using the selected item name (key), we are safely retrieving its effect (value) from another dictionary called item_effects.
In this way, using dict to manage data (items, effects, prices, etc.) and random to decide which data to manipulate is a very common practice in game development.
いいなと思ったら応援しよう!
よろしければ応援お願いします!いただいたチップはクリエイターとしての活動に使わせていただきます。
