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

如何实现用户输入否定指令时终止程序?当前代码未生效

问题解决:让程序在输入N/No/n/no时停止运行

你的代码问题出在while循环的条件判断逻辑上,原写法more != "N" or "No" or "n" or "no"完全不符合Python的逻辑判断规则——因为"No"、"n"、"no"都是非空字符串,在布尔判断里会被视为True,所以这个条件永远为True,循环根本停不下来。

修正方案

我们可以把所有需要触发停止的输入放到一个集合里,然后判断用户输入是否不在这个集合中,以此控制循环继续:

def Main():
    global more
    InitializeReport()
    TeamCode()
    # 定义所有需要停止程序的输入值
    stop_responses = {"N", "No", "n", "no"}
    more = input("Do you have more to enter?")

    # 当输入不在停止集合里时,继续循环
    while more not in stop_responses:
        ProcPlyr()
        more = input("Do you have more to enter?")
    CalcAvg()
    DisplaySummary()

额外优化(可选)

如果想忽略用户输入的大小写和多余空格(比如用户输入 NO 也能识别),可以对输入做预处理:

def Main():
    global more
    InitializeReport()
    TeamCode()
    stop_responses = {"n", "no"}
    more = input("Do you have more to enter?").strip().lower()

    while more not in stop_responses:
        ProcPlyr()
        more = input("Do you have more to enter?").strip().lower()
    CalcAvg()
    DisplaySummary()

这里用strip()去掉首尾空格,lower()把输入转成小写,这样不管用户输入NO、 n 都能触发停止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:20:37