You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hangman游戏while循环重复打印无法停止问题求助

Hangman游戏循环重复输出问题解决

核心原因很简单:你没有在while循环内部获取新的用户输入。

你当前的代码里,userInput应该是在循环外部定义的,循环启动后没有重新获取新输入的逻辑——这就导致每次循环都会用最开始的那个输入值来判断,不会等待用户输入新字母,自然会一直重复相同的输出内容,没法进行后续猜测。

修复方法

把获取用户输入的代码放到while循环的最开头,让每次循环都主动读取用户的新输入,比如添加这行:

userInput = input("Guess a letter: ").strip().lower()

修复后的完整循环代码示例:

while len(wordLetters) > 0 and lives > 0:
    # 关键:每次循环都获取新的用户输入
    userInput = input("Guess a letter: ").strip().lower()
    print(f'So far, you have guessed these letters: {usedLetters}')
    wordDisplay = [letter if letter in usedLetters else '-' for letter in word]
    print('Current word:', ' '.join(wordDisplay))
    print(visual_hangman[lives])
    
    if userInput in alphabet - usedLetters:
        usedLetters.add(userInput)
        if userInput in wordLetters:
            print('Correct!')
            wordLetters.remove(userInput)
        else:
            lives = lives - 1
            print(f'Sorry, that is incorrect. You now have {lives} guesses left.')

    elif userInput in usedLetters:
        print('You have already guessed this letter!')

    else:
        print('Invalid character! Please try again.')

这样每次循环时,程序都会先让用户输入新字母,再执行后续的判断和输出逻辑,就能正常进行多轮猜测了。

内容的提问来源于stack exchange,提问作者ChrisHart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:07:12