Weird behaviour of variable scope in Julia Loops

shwetank_verma
Sun, 17 Jul 2022 15:42:00 +0000
General Usage

Hey everyone,
I have noticed this peculiar behavior of variable scope inside the for loops in Julia. I am calling it peculiar as I have not seen this in Python.

Consider this Python code:

for i in range(1,10):
    if i == 1:
        print(i)
    else:
        print(x)

    x = 2

the output of this code is:

1
2
2
2
2
2
2
2
2

However, in Julia this code:

for i in 1:10
    if i==1
        print(i)
    else
        print(x)
    end

    x = 2

end

produces an error:
UndefVarError: x not defined

I want to understand why is this like this? I am currently solving this issue by creating a third variable outside the loop.
I am using Julia 1.7

2 posts - 2 participants