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'srangeis left-inclusive, right-exclusive — it stops right before reaching the second argument you pass. - The
i += 1line inside the loop is totally unnecessary (and doesn't do what you might expect!). When you usefor i in range(...), each iteration grabs the next value from a pre-generated sequence. Changingiinside 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 += 1line 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
相关产品推荐
相关产品推荐

