簡體   English   中英

While 與 For 循環計數器

[英]While vs For loop counter

剛開始學習 Python,但我想不出這背后的邏輯,我希望有人能澄清一下。

# this works without a counter
Numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for Numbers in Numbers:
     print(Numbers)

# this doesn't work without a counter
Numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
while Numbers in Numbers <= 5:
     print(Numbers)

那么“for 循環”可以遍歷每個值並報告它,但是“while 循環”不能嗎? 為什么'while循環'需要一個計數器變量來進行而for不需要? 我是否正確理解了這一點,如果是這樣,不連續是否有任何實際原因?

編輯:我很欣賞關於循環如何工作的評論,但這不是我的問題。 考慮之后,我想出了一個更好的方法來問我的問題,再次,如果這一切都變得無可救葯,我深表歉意,但我 3 天前才開始學習編碼/python。 所以之前我是從為什么 while 循環沒有與 for 循環相似的功能的方向來的,所以這里是來自相反方向的相同問題......如果 for 循環只是一個簡化的,為什么存在while循環?

#convince me this isn't a for loop, and if it is, why do for loops exist?
Numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x = 0
while x < len(Numbers):
     print(Numbers[x])
     x = x + 1

for loop基本上是一個一個地處理每個元素, while loop有點不同,它處理數據直到你的條件為真。 這里我們使用計數器作為條件,所以當while loop條件失敗時,循環可以停止工作。 所以基本上,如果你想一個一個地處理每個數據,你可以 go for for loop如果你想處理數據達到某個特定條件,你可以 go for while loop 前任。 如果您有 5 個元素並且必須處理所有元素,那么您可以使用 go for for loop ,如果您想多次或按動態順序處理數據,則可以使用while loop

while循環將循環直到條件為 False, for循環將循環直到遍歷列表中的所有元素。 一些示例如何使用它們:

打印數字 0 到 9 的 for 循環Number將引用列表Numbers中的元素

Numbers = range(10) #same result as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for Number in Numbers:
     print(Number)

打印數字 0 到 5 的 while 循環。 i將在列表中引用 position。

Numbers = range(10) #same result as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
i = 0
while Numbers[i] <= 5:
     print(Numbers[i])
     i += 1

又增加了一個例子,見下面的評論:

test = True
while test==True:
    number = input("Enter an int: (enter 0 to exit)\n")
    if number.isdigit(): # Checks if an int has been enterd
        number = int(number)
        if number == 0: # Exit the while loop if you enter 0 
            test = False
        else:
            for i in range(number):
                print(i)

那么“for 循環”可以遍歷每個值並報告它,但是“while 循環”不能嗎? 為什么'while循環'需要一個計數器變量來進行而for不需要?

我認為這里的斷開是while循環通常用於不能使用for循環的情況。 這是一個簡單的例子:

answer = input("Do you want to continue?")
while answer == yes:
    print("we are doing stuff..."
    answer = input("Do you want to continue?")

在這種情況下,計數器是沒有意義的,因為我們不知道循環將重復多少次。 我們也許能夠創建一個等效for循環,但它會不必要地復雜。

暫無
暫無

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

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