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

如何终止Python中的while循环?输入列表内容完成后退出循环

终止该Python无限while循环的方法

以下是几种简单可行的实现方式:

  • 检测特定输入触发退出
    约定一个终止指令(比如输入exit作为姓名值),获取输入后判断是否触发指令,一旦匹配就用break跳出循环。同时修正原代码中用list做变量名的问题(list是Python内置关键字,不能用作自定义变量名),修改后的代码示例:

    my_list = ["Alice", 100, "Bob", 200]
    while True :
        name = input()
        # 输入exit时直接终止循环
        if name == 'exit':
            break
        # 增加输入合法性判断,避免非数字输入报错
        try:
            d = int(input())
        except ValueError:
            print("请输入有效数字")
            continue
        found = False
        for i in range(0, len(my_list), 2):
            if my_list[i] == name:
                q = my_list[i+1] - d
                print(q)
                found = True
                break
        if not found:
            print("Wrong")
    
  • 通过快捷键强制终止
    捕获KeyboardInterrupt异常,支持用户用Ctrl+C快捷键终止循环:

    my_list = ["Alice", 100, "Bob", 200]
    try:
        while True :
            name = input()
            d = int(input())
            found = False
            for i in range(0, len(my_list), 2):
                if my_list[i] == name:
                    q = my_list[i+1]-d
                    print(q)
                    found = True
                    break
            if not found:
                print("Wrong")
    except KeyboardInterrupt:
        print("\n循环已终止")
    
  • 使用循环控制标志
    用布尔变量替代while True,通过修改标志状态终止循环:

    my_list = ["Alice", 100, "Bob", 200]
    running = True
    while running :
        name = input()
        if name == 'exit':
            running = False
            continue
        d = int(input())
        found = False
        for i in range(0, len(my_list), 2):
            if my_list[i] == name:
                q = my_list[i+1]-d
                print(q)
                found = True
                break
        if not found:
            print("Wrong")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:50:47