[Python] For loop overriding outer variables instead of creating new ones

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    I stumbled upon another basic concept I've missed in Python:

    Having this basic for (foreach) loop:

    x = 15
    for x in range(10):
    continue
    print(x)


    The value for x I expected was 15, but instead I got 9.

    The same code snippet in C returns x's original value – 15:

    #include <stdio.h>

    int main(void)
    {
    int x = 15;
    for (int x = 0; x < 10; x++)
    {
    continue;
    }
    printf("%d", x);
    return 0;
    }


    I can't figure out how the variable scope works here.

    Since x is declared outside the for loop scope, shouldn't a new local variable be created during the lifetime of the loop?

    Why is x being overridden in the Python version then?

    Continue reading...

Compartilhe esta Página