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

Python函数陷入死循环求助:执行时无法跳出循环

问题分析与解决

你的函数陷入死循环的核心原因是while条件的逻辑错误:
原代码中的while "-" or " " in word,由于"-"是一个非空字符串,在布尔判断中会被直接判定为True,导致整个while条件永远成立,循环无法终止。

正确的写法

需要明确判断目标单词中是否包含"-"或" ",有两种常见写法:

写法一:直接拆分判断

import random

def valid_word(words):
    word = random.choice(words)
    while "-" in word or " " in word:
        word = random.choice(words)
        print("Inside loop")
    return word.upper()

写法二:用any()简化判断(适合多字符检查场景)

import random

def valid_word(words):
    word = random.choice(words)
    # 检查单词是否包含指定的任意一个字符
    while any(char in word for char in ["-", " "]):
        word = random.choice(words)
        print("Inside loop")
    return word.upper()

额外注意

要确保传入的words列表中确实存在不包含"-"和" "的单词,否则即使条件修正,也会因为找不到符合要求的单词而持续循环。

内容的提问来源于stack exchange,提问作者Aditya-47

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:15:47