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

如何让while循环内的if条件判断正常生效?

问题分析与修复方案

核心问题

你的代码里i变量初始化在for c in range(start, end, 1)循环外面,导致第一次while循环执行完后,i就等于列表长度,后续的for循环迭代时,while循环直接跳过,完全没执行。

另外,当前逻辑会让同一个数字匹配多个列表元素时重复输出,比如数字15同时匹配列表里的"1"和"5",会输出两次15 → ,这可能不符合你的预期。

修复后的代码

ls = list()
qt = int(input('How many numbers you want to analyze: '))
for c in range(1, qt + 1):
    ls.append(input(f'Write the number you want to analyze: '))

start = int(input('First digit: '))
end = int(input('Last digit: '))

# 遍历指定范围内的每个数字
for num in range(start, end):
    num_str = str(num)
    # 每次检查新数字时,重新从列表开头遍历
    found = False
    for target in ls:
        if target in num_str:
            found = True
            break  # 只要匹配到一个就停止检查,避免重复输出
    if found:
        print(num_str, end=' → ')
print('Done')

关键修改点

  • 将列表遍历逻辑改成嵌套for循环,每次处理范围内的一个数字时,都重新遍历整个目标列表,避免i变量越界后不再执行的问题。
  • 增加found标记,确保每个符合条件的数字只输出一次,不管匹配到列表里多少个元素。
  • 变量名调整为更具可读性的命名,方便后续维护。

示例运行

假设输入:

How many numbers you want to analyze: 2
Write the number you want to analyze: 1
Write the number you want to analyze: 5
First digit: 10
Last digit: 20

输出会是:

10 → 11 → 12 → 13 → 14 → 15 → 16 → 17 → 18 → 19 → Done

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:05:55