Variable scope in for loop

Hi,
Please see the following code:

for i = 1:2
    a = 7
    for i = 3
        a = 9
    end
    @show a
    @show i
end

which has the output:

a = 9
i = 1
a = 9
i = 2

My question is, why is the value of “i” not modified by the inner for loop? I think its value should be modified just like what happened to variable “a”.

I’m using Julia 1.3.1

Thank you!

The relevant docs section is For Loops and Comprehensions.

What you want is:

for i = 1:2
    a = 7
    for outer i = 3
        a = 9
    end
    @show a
    @show i
end

Which gives:

a = 9
i = 3
a = 9
i = 3
1 Like

Thank you! Very helpful!

1 Like