Weird behaviour of variable scope in Julia Loops

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

The problem is that the variable x is undefined when the just-in-time (JIT) compiler tries to make sense of the code. For your example it would be enough to define x later, but the JIT compiler cannot predict that.

You could for example initialise the variable in an outer scope, e.g. by adding x = missing or x = 0 before the for loop.

(A small side note: range(1,10) is the same as 1:9, not 1:10)

2 Likes