Python猜词游戏:索引0处下划线无法被用户输入字母替换求助
问题:猜词游戏首字母无法被填充的解决方案
你的代码核心问题是大小写不匹配:
- 单词列表里的单词首字母是大写(比如"Apple"的'A')
- 用户输入的字母被强制转成了小写(
guess = input('Guess the letter: ').lower()) - 执行
letter == guess比较时,大写'A'和小写'a'判定为不相等,导致首字母位置永远无法被匹配填充。
另外还有一个细节bug:循环结束条件里的end_of_game == True是比较操作,不是赋值,应该改成end_of_game = True,否则即使猜完所有字母,循环也不会停止。
两种修复方案:
方案1:统一将目标单词转成小写
修改随机选单词的逻辑,把选中的单词直接转成小写,从根源上统一大小写:
chosen_word = random.choice(word_list).lower()
方案2:比较时统一转小写
保持原单词格式不变,在字母匹配时将目标字母也转成小写:
if letter.lower() == guess:
修复后的完整代码示例:
import random word_list = ['Lemon', 'Apple', 'Kiwi'] chosen_word = random.choice(word_list).lower() print(f'the solution is {chosen_word}.') display = ['_' for _ in range(len(chosen_word))] print(display) end_of_game = False while not end_of_game: guess = input('Guess the letter: ').lower() for position in range(len(chosen_word)): letter = chosen_word[position] if letter == guess: display[position] = letter print(display) if '_' not in display: end_of_game = True # 修正为赋值操作 print('You win')
内容的提问来源于stack exchange,提问作者Lemon Dhakal
相关产品推荐
相关产品推荐

