如何实现Python猜单词功能:错误输入则重启6次循环流程?
猜词游戏代码修改方案
你的需求是:目标单词flower有6个字母,最多允许6次猜词尝试,每次猜词错误就重新展示提示并让用户再次输入,直到猜对或用完次数。以下是修改后的代码及说明:
修改后的完整代码
word = 'flower' max_attempts = len(word) # 最多6次尝试 attempts = 0 while attempts < max_attempts: # 打印下划线提示 print("\nHint : ") print('_' * len(word)) print() # 获取用户猜词,先校验长度 guess = input('What is your guess? ') while len(guess) != len(word): guess = input('Please enter a word of correct length: ') # 检查猜词是否完全正确 if guess.lower() == word.lower(): print(f"\nCorrect! You guessed it in {attempts + 1} attempts.") break # 逐字符对比并展示结果 count = 0 result = [] while count < len(word): if guess[count].lower() not in word: result.append('_') elif guess[count].lower() == word[count]: result.append(guess[count].upper()) else: result.append(guess[count].lower()) count += 1 print(''.join(result)) attempts += 1 # 用完所有次数仍未猜对的情况 if attempts == max_attempts: print(f"\nYou've used all {max_attempts} attempts. The correct word was '{word}'.")
关键改动说明
- 外层循环控制尝试次数:用
while attempts < max_attempts确保最多运行6次 - 每次尝试前重新打印下划线提示,符合"错误输入则重启整个流程"的要求
- 增加了猜词完全正确的判断逻辑,猜对后直接结束游戏
- 修复了原代码中
count变量仅在else分支递增的bug,现在每个循环都会正确更新count - 用列表收集结果再拼接打印,比逐字符打印更清晰易读
- 补充了用完所有尝试次数的提示信息
内容的提问来源于stack exchange,提问作者HARISH S
相关产品推荐
相关产品推荐

