For what i understand (and is not a lot), there is a problem with the scope of the function, as the variables inside the loop can’t access variables outside the loop (for more information, you can read this discourse thread New Scope Solution ). One way is to directly use the variable using the global prefix:
x = 0
for i = 1:5
global x += 1
println(x)
end
But I recommend using directly the iterator:
for i = 1:5
println(i)
end
If you really need to use that x, you can make a function:
function myfn(x)
for i=1:5
println(x+i)
end
end
so, you have this
julia> myfn(2)
3
4
5
6
7
if you want the x modified, you can do something like this
function myfn!(x)
#in julia, the ! means that the function modifies the argument, generally the first one
for i=1:4 # the return statement prints x
x+=1
println(x)
end
return x
end
For now, I think the easiest thing to do is either (1) stick in Jupyter for these sorts of interactive code, and (2) wrap anything that involves for or while loops in functions (e.g.
function f()
x = 0
while x < 5
x += 1
println(x)
end
end
f()
Encounterd similar behaviour, this is very unintuitive - own scope in for loop. Should be writing in big font in docs about this or through an instructive exception.
One rather important distinction between the previous while loop form and the for loop form is the scope during which the variable is visible. If the variable i has not been introduced in another scope, in the for loop form, it is visible only inside of the for loop, and not outside/afterwards.