"""
Python3基礎認定試験対策 - メソッド問題集
メソッド名から正しい説明の番号を選択するクイズアプリ
"""
import random
class MethodQuiz:
def __init__(self):
self.method_data = [
["append", "リストの末尾にアイテムを一つ追加"],
["extend", "末尾にイテラブルの全アイテムを追加"],
["insert", "指定された位置にアイテムを挿入"],
["remove", "引き数に等しい最初のアイテムを削除"],
["pop", "デフォルトで最後のアイテムを削除・リターンする"],
["clear", "空リストにする"],
["index", "引き数に等しい最初のインデックスを返す"],
["count", "リスト内の引数に等しい値の数を返す"],
["sort", "デフォルトで昇順に並べる"],
["reverse", "要素の順序を逆順にする"],
["copy", "浅いコピーで、使い方で注意もある!"]
]
self.score = 0
self.total_questions = 0
def create_question(self):
"""問題を作成する(ランダム選択)"""
# ランダムに問題を選択
correct_method = random.choice(self.method_data)
return self.create_question_for_method(correct_method)
@staticmethod
def display_question(method_name, choices):
"""問題を表示する"""
print("\n" + "=" * 50)
print(f"【問題】 メソッド: {method_name}")
print("=" * 50)
print("以下の説明の中から、正しいものの番号を入力してください:")
print()
for i, choice in enumerate(choices, 1):
print(f"{i}. {choice}")
print()
@staticmethod
def get_user_answer(max_choice):
"""ユーザーの回答を取得する"""
while True:
try:
answer = input(
f"答えを入力してください (1-{max_choice}): ").strip()
if answer.lower() in ['q', 'quit', '終了']:
return None
answer_num = int(answer)
if 1 <= answer_num <= max_choice:
return answer_num
else:
print(f"1から{max_choice}の間で入力してください。")
except ValueError:
print(
"数字を入力してください。\
終了する場合は 'q' を入力してください。")
def display_result(self, user_answer, correct_answer, method_name,
choices):
"""結果を表示する"""
if user_answer == correct_answer:
print("✅ 正解です!")
self.score += 1
else:
print("❌ 不正解です。")
print(f"正解は {correct_answer}. "
f"{choices[correct_answer - 1]} でした。")
print(f"メソッド '{method_name}' の正しい説明: "
f"{choices[correct_answer - 1]}")
def display_final_score(self):
"""最終スコアを表示する"""
print("\n" + "=" * 50)
print("【テスト結果】")
print("=" * 50)
print(f"正解数: {self.score}/{self.total_questions}")
if self.total_questions > 0:
percentage = (self.score / self.total_questions) * 100
print(f"正答率: {percentage:.1f}%")
if percentage >= 90:
print("🎉 素晴らしい!完璧に近い理解です!")
elif percentage >= 70:
print("👏 良くできました!もう少しで完璧です!")
elif percentage >= 50:
print("📚 もう少し復習が必要ですね。頑張りましょう!")
else:
print("💪 基礎からしっかり復習しましょう!")
def run_all_questions(self):
"""全ての問題を実行する(11問モード)"""
print("\n📚 全ての問題にチャレンジします!(11問)")
print("=" * 50)
# 全てのメソッドをランダムな順番で出題
all_methods = self.method_data.copy()
random.shuffle(all_methods)
try:
for i, method_info in enumerate(all_methods, 1):
print(f"\n【問題 {i}/11】")
question_data = self.create_question_for_method(
method_info)
method_name, choices, correct_answer = question_data
# 問題表示
self.display_question(method_name, choices)
# 回答取得
user_answer = self.get_user_answer(len(choices))
if user_answer is None: # 終了
print("テストを中断しました。")
break
self.total_questions += 1
# 結果表示
self.display_result(user_answer, correct_answer,
method_name, choices)
# 最後の問題でなければ次へ進む確認
if i < len(all_methods):
input("\n次の問題に進みます... (Enterキー)")
except KeyboardInterrupt:
print("\n\nテストを中断しました。")
def create_question_for_method(self, method_info):
"""指定されたメソッドの問題を作成する"""
correct_answer = method_info
# 選択肢を作成(正解 + ランダムな3つの不正解)
choices = [correct_answer[1]] # 正解の説明
other_descriptions = [item[1] for item in self.method_data
if item != correct_answer]
# ランダムに3つの不正解を選択
wrong_choices = random.sample(other_descriptions,
min(3, len(other_descriptions)))
choices.extend(wrong_choices)
# 選択肢をシャッフル
random.shuffle(choices)
# 正解の位置を記録
correct_index = choices.index(correct_answer[1]) + 1
return correct_answer[0], choices, correct_index
def run_random_quiz(self):
"""ランダム問題モード"""
print("\n🎲 ランダム問題モード")
print("=" * 50)
print("終了する場合は 'q' を入力してください。")
try:
while True:
# 問題作成
question_data = self.create_question()
method_name, choices, correct_answer = question_data
# 問題表示
self.display_question(method_name, choices)
# 回答取得
user_answer = self.get_user_answer(len(choices))
if user_answer is None: # 終了
break
self.total_questions += 1
# 結果表示
self.display_result(user_answer, correct_answer,
method_name, choices)
# 続行確認
print("\n続けますか? (Enter: 続行, q: 終了)")
continue_input = input().strip().lower()
if continue_input in ['q', 'quit', '終了']:
break
except KeyboardInterrupt:
print("\n\nテストを中断しました。")
def run_quiz(self):
"""クイズを実行する"""
print("🐍 Python3基礎認定試験対策 - リストメソッド問題集")
print("=" * 60)
print("各メソッドの正しい説明を選択してください。")
# モード選択
print("\n📋 学習モードを選択してください:")
print("y: 全ての問題をやる(11問すべて)")
print("n: ランダム問題モード(好きなだけ)")
while True:
choice = input("\n全ての問題をやりますか(11問)? (y/n): ")
mode_choice = choice.strip().lower()
if mode_choice in ['y', 'yes', 'はい']:
self.run_all_questions()
break
elif mode_choice in ['n', 'no', 'いいえ']:
self.run_random_quiz()
break
else:
print("'y' または 'n' を入力してください。")
# 最終結果表示
if self.total_questions > 0:
self.display_final_score()
print("\nお疲れ様でした!Python3基礎認定試験頑張ってください!🎯")
def main():
"""メイン関数"""
quiz = MethodQuiz()
quiz.run_quiz()
if __name__ == "__main__":
main()