Home > OS >  While vs For loop counter
While vs For loop counter

Time:04-13

Just starting out with learning Python, but I can't come up with the logic behind this and I was hoping someone could clarify.

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

But

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

So 'for loop' can progress through each value and report it, but 'while-loop' can't? Why does 'while loop' require a counter variable to progress when for doesn't? Am I understanding this correctly, and if so, is there any practical reason for the discontinuity?

CodePudding user response:

for loop is basically process each element one by one and while loop is little bit different, it process the data until your condition is true. Here we used counter as condition so when while loop condition going to fail loop can stop working. So basically if you want to process each data one by one you can go for for loop and if you want to process data up to some certain condition you can go for while loop. ex. if you have 5 element and you have to process all then you can go for for loop and if you want to process data multiple time or in dynamic sequence you can use while loop.

CodePudding user response:

A while loop will loop until the condition is False and a for loop will loop until you have looped through all elements in the list. Some exemples how you can use them:

A for loop that prints the numbers 0 to 9. Number will reference the element in the list Numbers

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

A while loop that prints the numbers 0 to 5. i will reference the position in the list.

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