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

无法退出While True循环:打印日期后仍持续请求输入

问题分析

你代码里的break语句只跳出了内层的for循环,外层的while True循环并没有被终止,所以打印完日期后,程序会继续执行input("Enter: "),导致持续显示提示。

解决方案

需要在外层的while循环中添加终止逻辑,以下是两种可行的修改方式:

方式一:利用for-else结构

当for循环通过break跳出时,不会执行else块,此时直接终止外层while循环:

while True:
    user = input("Enter: ")
    if "/" not in user:
        if "," in user:
            date = user.replace(",", "")
        date = date.split(" ")
        date = list(date)
        for i in range(len(date)):
            if date[i] in month:
                mnth = month[f"{date[i]}"]
                if int(date[1]) < 10:
                    date[1] = "0" + date[1]
                print(f"{date[2]}-{mnth}-{date[1]}")
                break  # 跳出内层for循环
        else:
            # 若for循环未触发break,继续外层循环
            continue
        # 触发了for的break,终止外层while循环
        break

方式二:使用标志位

设置一个布尔变量标记是否成功处理日期,处理完成后终止外层循环:

while True:
    user = input("Enter: ")
    processed = False
    if "/" not in user:
        if "," in user:
            date = user.replace(",", "")
        date = date.split(" ")
        date = list(date)
        for i in range(len(date)):
            if date[i] in month:
                mnth = month[f"{date[i]}"]
                if int(date[1]) < 10:
                    date[1] = "0" + date[1]
                print(f"{date[2]}-{mnth}-{date[1]}")
                processed = True
                break
    if processed:
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:16:38