簡體   English   中英

循環從 python continue 語句中的 2 而不是 1 開始

[英]Loop start from 2 instead of 1 in python continue statement

我正在學習 python while 循環中的 continue 語句。 如果我運行以下代碼,則 output 顯示為 2 而不是 1。

    a = 1
    while a <= 8:
        a += 1
        if a == 5:
            continue
        print(a)

你 go 通過 while 條件的主體一次,1 + 1 = 2 然后打印(2)

a += 1 出現在 print 語句之前,這就是它打印 2 的原因。你的 a == 5 條件也沒有執行,因為 a 是 2。

如果您還沒有得到答案,您可以詳細說明您的問題。

您當前的代碼在下面,我用 a 的值對其進行了注釋

a = 1 #### a is 1 here obviously ####
while a <= 8:
    a += 1 #### a is incremented by 1, so the value of a is 2 here ####
    if a == 5:
        continue
    print(a) #### the value of a is 2 when you print ####

讓計數器從 1 開始:

a = 1 #### a is 1 here obviously ####
while a <= 8:
    # remove this step that increments a #### value of a is still 1
    if a == 5:
        continue
    print(a) #### the value of a is 1 when you print ####
    a += 1 # increment a here instead

暫無
暫無

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

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