1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] While vs For loop counter

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 13:32.

  1. Stack

    Stack Membro Participativo

    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?

    EDIT: I appreciate the comments about how the loops work but that's not really my question. After thinking about it, I think I came up with a better way to ask my question, and again, I apologize if this all comes off as hopelessly ignorant, but I only started learning coding/python 3 days ago. So previously I was coming at it from the direction of why while-loops don't have similar functionality to for-loops, so here's the same question from the opposite direction... Why do for-loops exist if they are just a simplified while-loop?

    #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

    Continue reading...

Compartilhe esta Página