"UndefVarError: V not defined" using simple loop

I stuck in my very first lines. Why V is not visible inside the loop? What is the logic behind that?

V=1
for i in 1:2
print(V)
V=2
end

ps Matlab background

I recommend working within the REPL where you have global softscope.

julia> V=1
       for i in 1:2
       print(V)
       V=2
       end
12

Outside of the REPL, you need to declare V as a global within the for loop. Alternatively and preferably, execute this within a function.

2 Likes

Here is how you can explicitly declare a global within the for loop. Note this is not recommended and is a recipe for slow code.

PS C:\Users\kittisopikulm> julia -e'
>> V=1
>> for i in 1:2
>> print(V)
>> V=2
>> end
>> '
┌ Warning: Assignment to `V` in soft scope is ambiguous because a global variable by the same name exists: `V` will be treated as a new local. Disambiguate by using `local V` to suppress this warning or `global V` to assign to the existing global variable.
└ @ none:5
ERROR: UndefVarError: V not defined
Stacktrace:
 [1] top-level scope
   @ .\none:4
PS C:\Users\kittisopikulm>
PS C:\Users\kittisopikulm> julia -e'
>> V=1
>> for i in 1:2
>> global V
>> print(V)
>> V=2
>> end
>> '
12

If you put everything into a function, then this works within the function’s local scope.

PS C:\Users\kittisopikulm> julia -e'
>> function foo()
>>
>> V=1
>> for i in 1:2
>> print(V)
>> V=2
>> end
>>
>> end
>>
>> foo()
>> '
12

For more information, see Scope of Variables · The Julia Language

Thank you for instant answer.