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

为何While循环在display无下划线的条件满足后仍无限运行?

问题分析与解决:while循环无法正常终止

你的代码里,循环无法终止的核心原因是遍历display的方式错误:

  • 用for item in display遍历列表时,item是遍历那一刻列表元素的副本,后续display列表更新后,item不会同步变化。
  • 比如一开始display是['_','_','_'],第一个item是'_',进入while item == "_"循环后,哪怕后续display被更新为没有下划线的状态,item的值还是最初的'_',导致while循环永远不会退出。

修正方案

把外层的for循环去掉,改成直接检查整个display列表中是否还存在下划线,用while循环持续判断这个条件:

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

print(f'Pssst, the solution is {chosen_word}.')

display = []
for _ in range(word_length):
    display += "_"

guess = input("Guess a letter: ").lower()

def check_letter():
    for position in range(word_length):
        letter = chosen_word[position]
        if letter == guess:
            display[position] = letter
    print(display)

check_letter()

# 修正:直接检查display中是否还有下划线
while "_" in display:
    guess = input("Guess a letter: ").lower()
    check_letter()

print("You've Won")

说明

  • 用"_" in display作为while循环的判断条件,每次循环都会重新检查当前display列表的状态,只要还有下划线就继续运行,没有则终止循环。
  • 去掉了多余的for循环,避免了元素副本导致的判断失效问题。

内容的提问来源于stack exchange,提问作者scott.piligrim2018

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:14:37