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

Python入门咨询:如何用range循环生成0、2、4…50的偶数序列

How to Generate Even Numbers from 0 to 50 in Python

Hey there! Let's break down what's going on with your code and fix it to get the exact sequence you want (0, 2, 4, ..., 50).

First, let's spot the two key issues in your current code:

  • The range(0, 50, 2) will only go up to 48, not 50. Python's range is left-inclusive, right-exclusive — it stops right before reaching the second argument you pass.
  • The i += 1 line inside the loop is totally unnecessary (and doesn't do what you might expect!). When you use for i in range(...), each iteration grabs the next value from a pre-generated sequence. Changing i inside the loop won't affect the next value pulled from the range at all.

The Fixed Code

Here's the simple, correct version that prints every even number from 0 to 50 (inclusive):

for i in range(0, 51, 2):
    print(i)

Why This Works

  • range(0, 51, 2) starts at 0, stops just before 51 (so it includes 50), and steps by 2 each time — exactly the sequence you're aiming for.
  • We removed the i += 1 line because it was adding confusion without serving any purpose here.

Bonus: Store the Sequence in a List

If you want to save the even numbers as a list instead of just printing them one by one, you can use a list comprehension:

even_numbers = [i for i in range(0, 51, 2)]
print(even_numbers)

This gives you a reusable list [0, 2, 4, ..., 50] that you can work with later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:10:16