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

如何编写双条件while循环?我的多条件循环逻辑异常求助

问题修复:while循环条件逻辑错误

问题现象

使用while type != "video" or type!= "audio":时循环无法正常终止,但单独用while type != "video":时功能正常。

错误原因

原条件逻辑存在矛盾:

  • 输入video时,type != "audio"为真,整个or条件结果为真,循环持续执行
  • 输入audio时,type != "video"为真,整个or条件结果为真,循环持续执行
  • 输入任何值都会满足这个or条件,导致循环永远无法退出

修复方案

提供两种简洁的修复方式:

方式1:改用and逻辑

将or替换为and,表示既不是video也不是audio时才进入循环:

type = input("Do you want a video or an audio? (answer by video or audio)\n >> ")
while type != "video" and type != "audio":
    print('Error! select an existing type')
    type = input("Do you want a video or an audio? (answer by video or audio)\n >> ")
if type == "video":
    video_dwld()
elif type == "audio":
    audio_dwld()

方式2:用not in判断(更简洁易读)

直接判断输入是否不在允许的选项列表中:

type = input("Do you want a video or an audio? (answer by video or audio)\n >> ")
while type not in ["video", "audio"]:
    print('Error! select an existing type')
    type = input("Do you want a video or an audio? (answer by video or audio)\n >> ")
if type == "video":
    video_dwld()
elif type == "audio":
    audio_dwld()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:40:40