Python猜词游戏输出重复拼接问题排查与优化咨询
猜词游戏代码问题排查与优化
问题描述
我刚开始学习编程,要开发一个猜词游戏(Secret Word Game),但运行代码时结果总是重复拼接,本该只显示一次当前的猜词进度。请问我哪里出错了?以下是代码及控制台现象,同时欢迎其他优化建议。
原代码
print('¨' * 40) print(f'|{"Secret Word Game":^38}|') print('¨' * 40) secret_word = 'believer' user_input = '' typed = [] attempts= 0 number_of_letters = '_ ' * len(secret_word) discovering_secret_word = '' print('Try to guess the Secret Word!') print(f'The secret word is: {number_of_letters}') while discovering_secret_word != secret_word: user_input = input('Type a letter: ') attempts += 1 if len(user_input) > 1: print('You can´t insert more than one letter!') continue typed.append(user_input) for letter in secret_word: if letter in typed: discovering_secret_word += letter # 原代码此处为笔误,写了letra else: discovering_secret_word += '_ ' print(f'The Secret Word is {discovering_secret_word}') else: print('Congratulations, you won!') print(f'The Secret Word is {secret_word}.') print(f'It took {attempts} attempts.')
控制台现象
每次输入字母后,猜词进度会重复拼接:比如第一次输入b后显示b _ _ _ _ _ _ _ _,第二次输入e后,会变成b _ _ _ _ _ _ _ _b e _ _ e _ _ e _,进度条无限变长,无法正确匹配目标单词。
问题原因
核心问题是**discovering_secret_word变量未在每次循环时重置**:
每次循环都会在该变量原有内容上追加新字符,而非重新构建当前的猜词进度,导致内容重复累积。
修复方案
将discovering_secret_word的初始化移到while循环内部,每次循环开始时清空并重新构建进度字符串,同时修正进度与目标单词的匹配逻辑(原进度带空格,需去除后再比较):
print('¨' * 40) print(f'|{"Secret Word Game":^38}|') print('¨' * 40) secret_word = 'believer' user_input = '' typed = [] attempts= 0 number_of_letters = '_ ' * len(secret_word) print('Try to guess the Secret Word!') print(f'The secret word is: {number_of_letters}') while True: # 每次循环重置进度字符串,重新构建当前猜词状态 discovering_secret_word = '' for letter in secret_word: discovering_secret_word += letter if letter in typed else '_ ' # 去除空格后与目标单词比较,判断是否猜中 if discovering_secret_word.replace(' ', '') == secret_word: break user_input = input('Type a letter: ') attempts += 1 if len(user_input) > 1: print('You can´t insert more than one letter!') attempts -= 1 # 错误输入不消耗尝试次数 continue user_input = user_input.lower() # 统一转小写,避免大小写敏感 if user_input in typed: print('You already typed this letter!') attempts -= 1 # 重复输入不消耗尝试次数 continue typed.append(user_input) print(f'The Secret Word is {discovering_secret_word}') print('Congratulations, you won!') print(f'The Secret Word is {secret_word}.') print(f'It took {attempts} attempts.')
其他优化建议
- 大小写兼容:将用户输入转为小写(或大写),避免
B和b被判定为不同字母 - 重复输入拦截:检测到重复输入时提示用户,且不增加尝试次数
- 逻辑顺序调整:先构建进度并判断是否胜利,再接收用户输入,逻辑更清晰
- 笔误修正:原代码中
letra是拼写错误,需改为letter
内容的提问来源于stack exchange,提问作者Ana Cristina
相关产品推荐
相关产品推荐

