what happened when using the same variable in two layer loops in python?

前端 未结 6 1674
星月不相逢
星月不相逢 2021-01-12 14:18

I test the following code:

for i in range(3):
    for i in range(3,5):
        print \"inner i: %d\"%(i)
    print \"outer i: %d\"%(i)

and

6条回答
  •  心在旅途
    2021-01-12 14:31

    It's the same i, Python doesn't have block scope. At the beginning of each for-loop iteration, you assign the the next value in the iterator to i. Python for-loops aren't like C/Java for-loops, they are foreach loops. The continue until the iterator is exhausted (or you break out somehow). A for-loop is equivalent to the following while-loop:

    iterator = iter(my_iterable)
    while True:
        try:
            x = next(iterator)
        except StopIteration:
            break
        do_stuff(x)
    

    So, your nested loop is the equivalent of this:

    it1 = iter(range(3))
    while True:
        try:
            i = next(it1)
        except StopIteration:
            break
    
        it2 = iter(range(3, 5))
        while True:
            try:
                i = next(it2)
            except StopIteration:
                break
            print "inner i: %d"%(i)
    
        print "outer i after: %d"%(i)
    

    Note, a C/Java for-loop, e.g.:

    for (int i = 0; i < stop; i++){
        do_stuff(i);
    }
    

    Would be in Python:

    i = 0
    while i < stop:
       do_stuff(i)
       i += 1
    

    In other words, the classic-for-loop depends on i, that is, the termination condition depends on the value of i. But in a for-each loop, the termination condition depends on the iterator. And it doesn't matter what you do to the variable inside the body, at the beginning of each iteration, it is assigned the next value of the iterator.

提交回复
热议问题