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

Python实现范围偶数正/逆序打印是否需要额外循环?

简洁实现方法

你可以通过动态调整步长和遍历起始值的方式,用单个循环处理正序和逆序两种情况,不需要写两个独立循环。以下是两种优化后的实现:

方式一:使用while循环

start = int(input("1st number: "))
end = int(input("2nd number: "))

# 确定遍历方向(步长)
step = 1 if start <= end else -1

# 找到第一个需要打印的偶数
if start % 2 == 0:
    current = start
else:
    # 正序时取start的下一个偶数,逆序时取start的上一个偶数
    current = start + step

# 遍历并打印所有符合条件的偶数
while (step == 1 and current <= end) or (step == -1 and current >= end):
    print(current, end=' ')
    current += step * 2

方式二:使用range函数(更符合Python风格)

start = int(input("1st number: "))
end = int(input("2nd number: "))

step = 1 if start <= end else -1

# 计算起始偶数
start_even = start if start % 2 == 0 else start + step
# 调整结束边界,确保range能包含end附近的最后一个偶数
end_bound = end + step if step == 1 else end - step

for num in range(start_even, end_bound, step * 2):
    print(num, end=' ')

思路说明

  1. 步长判断:根据start和end的大小决定步长是1(正序遍历)还是-1(逆序遍历)。
  2. 起始偶数计算:如果start本身是偶数就直接使用,否则根据步长调整到最近的符合方向的偶数(正序加1,逆序减1)。
  3. 遍历范围优化:用step*2作为遍历步长(每次跳过一个奇数,只取偶数),同时调整range的结束边界,确保能覆盖到end附近的最后一个偶数。

这种方式仅需一个循环,代码简洁逻辑清晰,同时覆盖了正序和逆序的打印需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:25:25