簡體   English   中英

如何使用 while 循環打印偶數 2 到 100?

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

我是一個初學者,我被這個問題困住了,“編寫一個使用 while 循環打印從 2 到 100 的偶數的 python 代碼。提示 ConsecutiveEven 相差 2。”

這是我到目前為止的想法:

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

使用for with range() ,或使用while並顯式增加數字。 例如:

>>> 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

這就是我要嘗試的:

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

下面是使用while循環的方法

 while [condition]:
     logic here

在范圍內使用 while 是不正確的。

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

您的代碼有幾個問題:

  • for語法替換while語句。 while需要一個布爾值,而不是可迭代的。
  • 使用不正確的range值:您將從 22 開始。

只需很少的更改,這應該可以工作:

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

請注意,我使用101作為range上限,因為它是exclude 如果我放100它會停在98

如果您需要使用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