当前位置:首页>python>Python每日1语法·Day5

Python每日1语法·Day5

  • 2026-09-10 13:30:30
Python每日1语法·Day5

【Python每日1语法·Day5】

结合 for + enumerate()|进阶版反转猜词小游戏(难度分级+答错重答+超时提示)


1. 今日核心升级:语法融合+逻辑进阶

在基础for + enumerate()之上,新增核心知识点:

  • enumerate() 结合列表切片实现“难度分组”;
  • 循环嵌套(for+while)实现“答错重答”;
  • 引入time模块实现答题计时(新手只需调用,不用深究原理);
  • 用sum()计算难度加权得分,提升游戏实用性。

游戏核心规则(难度升级):

  1. 分「简单(短单词)、中等(中单词)、困难(长单词)」3个难度,每轮随机分配;
  2. 每题有1次重答机会,重答仍错才扣分;
  3. 答题超时(5秒)直接判定错误;
  4. 按难度加权计分(简单1分、中等2分、困难3分),最后输出总分和评级。

2. 完整进阶版游戏代码(直接复制运行)

import randomimport time  # 计时模块# 步骤1:按难度分组单词库(长度区分难度)word_lib = {"简单": ["cat", "dog", "pen", "book", "egg"],  # 3-4个字符"中等": ["apple", "banana", "grape", "hello", "milk"],  # 5-6个字符"困难": ["watermelon", "chocolate", "elephant", "umbrella", "computer"]  # 7+字符}# 难度对应分值score_map = {"简单": 1, "中等": 2, "困难": 3}# 步骤2:游戏初始化total_round = 4# 总答题轮数total_score = 0# 总得分wrong_detail = []  # 答错详情(含难度、单词、正确答案)timeout_threshold = 5# 答题超时阈值(5秒)print("🎮 进阶版反转猜词小游戏(共{}轮)🎮".format(total_round))print("📌 规则:简单题1分/中等题2分/困难题3分|每题1次重答机会|答题超时直接错")print("——————————————————")# 步骤3:for + enumerate() 实现多轮+难度随机分配for round_num, _ in enumerate(range(total_round), start=1):# 随机选难度+对应单词    difficulty = random.choice(list(word_lib.keys()))    target_word = random.choice(word_lib[difficulty])    reverse_correct = ''.join(reversed(target_word))    current_score = score_map[difficulty]  # 本题分值    retry_count = 0# 重答次数(最多1次)    is_correct = False# 本题是否答对    timeout_flag = False# 是否超时    print(f"\n【第{round_num}题|{difficulty}难度|分值{current_score}分】")    print(f"请输入单词「{target_word}」的反转形式({timeout_threshold}秒内作答):")# 计时答题    start_time = time.time()  # 记录开始时间try:        user_answer = input("你的答案:")        end_time = time.time()  # 记录结束时间        used_time = round(end_time - start_time, 1)  # 计算用时(保留1位小数)# 步骤4:超时判断if used_time > timeout_threshold:            timeout_flag = True            print(f"⏰ 答题超时!你用了{used_time}秒(超时阈值{timeout_threshold}秒)")else:            print(f"⏱️ 答题用时:{used_time}秒")# 步骤5:答案验证 + 答错重答(while循环实现)while retry_count < 1:  # 最多重答1次# 长度校验(基础过滤)if len(user_answer) != len(target_word):                    print(f"⚠️ 答案长度错误!原单词有{len(target_word)}个字符")elif user_answer.lower() == reverse_correct.lower():                    is_correct = True                    print("🎉 答对啦!")breakelse:                    retry_count += 1if retry_count == 1:                        print(f"❌ 答错啦!你还有1次重答机会")                        user_answer = input("重答答案:")else:                        print(f"❌ 重答也错了~")# 步骤6:判定最终结果if is_correct:                total_score += current_score  # 加分else:# 记录答错详情                wrong_detail.append({"轮次": round_num,"难度": difficulty,"单词": target_word,"正确答案": reverse_correct,"超时": timeout_flag                })except:        print("⚠️ 输入异常,本题按答错处理")        wrong_detail.append({"轮次": round_num,"难度": difficulty,"单词": target_word,"正确答案": reverse_correct,"超时": False        })# 步骤7:结果统计与展示print("\n——————————————————")print("🎯 游戏结束!结算结果:")print(f"总答题数:{total_round} 题")print(f"总得分:{total_score} 分(满分{sum(score_map.values())*total_round//3*3}分)")  # 满分按平均难度计算# 评级逻辑max_possible_score = sum(score_map.values()) * total_round // 3 * 3# 简化满分计算rating = "未达标"if total_score >= max_possible_score * 0.9:    rating = "💎 大神级"elif total_score >= max_possible_score * 0.7:    rating = "🌟 优秀级"elif total_score >= max_possible_score * 0.5:    rating = "👍 合格级"print(f"评级:{rating}")# 答错详情展示(enumerate遍历展示)if wrong_detail:    print("\n📝 答错/超时题目详情:")for idx, detail in enumerate(wrong_detail, start=1):        timeout_note = "(超时)"if detail["超时"] else""        print(f"{idx}. 第{detail['轮次']}题({detail['难度']}):{detail['单词']} → 正确答案:{detail['正确答案']}{timeout_note}")else:    print("\n✨ 全部答对,太牛啦!")print("\n💡 小提示:长单词反转可以分段记,比如watermelon拆成water+melon再反转~")

3. 核心难点拆解(新手重点理解)

代码段
核心逻辑
新手注意点
word_lib = {"简单": [...], ...}
字典分组存储不同难度单词
字典键值对的取值方式:word_lib[difficulty]
time.time()
 计时
计算答题耗时
不用深究time模块原理,会调用start_time/end_time即可
while retry_count < 1
实现答错重答(最多1次)
循环嵌套:for外层控制轮数,while内层控制重答,注意缩进
sum(score_map.values())
计算难度分值总和
sum()
不仅能加数字列表,还能加字典值(需转成可迭代对象)
enumerate(wrong_detail, start=1)
遍历答错详情并编号
嵌套数据(字典列表)的遍历,重点是取字典的key值

4. 今日挑战练习(高阶拓展,锻炼逻辑)

要求:在进阶版基础上,新增2个功能(综合运用已学语法):

  1. 单词去重:答题过程中,已出过的单词不再重复出现;
  2. 连续答对奖励:连续答对2题及以上,额外加1分/次。

参考思路(关键代码片段):

# 新增:已出题单词列表used_words = []# 在选单词处增加去重逻辑whileTrue:    target_word = random.choice(word_lib[difficulty])if target_word notin used_words:        used_words.append(target_word)break# 新增:连续答对计数器continuous_correct = 0# 答对后更新连续计数器if is_correct:    continuous_correct += 1    total_score += current_score# 连续答对奖励if continuous_correct >= 2:        total_score += 1        print(f"🎁 连续答对{continuous_correct}题,额外加1分!")else:    continuous_correct = 0# 答错重置

最新文章

随机文章