簡體   English   中英

我在 python 中的 while 循環和 for 循環得到了不同的結果(檢查代碼)

[英]I got different results for a while loop and for loop in python (check the codes)

對於第一個代碼:

num = 1

while num<=100:
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")
    num+=1

輸出: 1 2

對於第二個代碼:

for num in range(1, 101):
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")

輸出:

1 2 4 7 8 11 13 14 16 17 19 22 23 26 28 29 31 32 34 37 38 41 43 44 46 47 49 52 53 
56 58 59 61 62 64 67 68 71 73 74 76 77 79 82 83 86 88 89 91 92 94 97 98

您需要編輯while代碼才能獲得相同的結果。 在您的while循環中,如果num%3 == 0 or num%==5 ,則程序不執行num += 1 ,因此您的程序不會增加 1。您需要像這樣更改:

num=0
while num <= 100:
    num+=1
    if num%3==0 or num%5==0:
        continue

    print (num, end=" ")

在繼續之前,您需要添加增量

num = 1
while num<=100:
    if num%3==0 or num%5==0:
        num += 1
        continue
    print (num)
    num+=1

您的代碼不會在 if 語句內的 while 循環中調用增量 1,它永遠不會超過 3。

這是一個無限循環。 您的程序在達到 num == 3 后永遠不會終止。它轉到 if 語句,而 continue 將其帶回 while 檢查。

使用以下邏輯

        num = 1

        while num <= 100:
            if num % 3 == 0 or num % 5 == 0:
                num += 1
                continue
            print(num, end=" ")
            num += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM