简体   繁体   English

如何使用 while 循环打印偶数 2 到 100?

[英]How is it possible to use a while loop to print even numbers 2 through 100?

I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."我是一个初学者,我被这个问题困住了,“编写一个使用 while 循环打印从 2 到 100 的偶数的 python 代码。提示 ConsecutiveEven 相差 2。”

Here is what I came up with so far:这是我到目前为止的想法:

 while num in range(22,101,2):
              print(num)

Use either for with range() , or use while and explicitly increment the number.使用for with range() ,或使用while并显式增加数字。 For example:例如:

>>> i = 2
>>> while i <=10: # Using while
...    print(i)
...    i += 2
...
2
4
6
8
10

>>> for i in range(2, 11, 2): # Using for
...    print(i)
...
2
4
6
8
10

This is what I'd try:这就是我要尝试的:

i=2
while i <= 100:
    if ( i % 2==0):
        print (i, end=', ')
    i+=1

Here is how to use the while loop下面是使用while循环的方法

 while [condition]:
     logic here

using while in range is incorrect.在范围内使用 while 是不正确的。

num = 0
while num <=100:
    if num % 2 == 0:
        print(num)
    num += 1

Your code has several problems:您的代码有几个问题:

  • Substituting while for a statement with for syntax.for语法替换while语句。 while takes a bool, not an iterable. while需要一个布尔值,而不是可迭代的。
  • Using incorrect values for range : you will start at 22.使用不正确的range值:您将从 22 开始。

With minimal changes, this should work:只需很少的更改,这应该可以工作:

for num in range(2, 101, 2):
    print(num)

Note that I used 101 for the upper limit of range because it is exclusive .请注意,我使用101作为range上限,因为它是exclude If I put 100 it would stop at 98 .如果我放100它会停在98

If you need to use a while loop:如果您需要使用while循环:

n = 2
while n <= 100:
    print (n)
    n += 2

使用 for while 编写一个只显示 1 到 20 的偶数的函数。确保你的函数被称为打印机

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM