Global variables not accessible inside loop

I am trying to execute this simple lines of code, but keep getting an undef error, although I explicitly define my variable to be global.

global t = 1;
for i in 1:10
t+=0.1;print(“\ni=”,i,“, t=”,t);
end

This gives

ERROR: UndefVarError: t not defined
I am using Julia 1.1.0. Can you help me understand what I am doing wrong.

You need global t += 0.1 in the loop to modify a global.

The keyword global is at the wrong place.

t = 1;
for i in 1:100  
    global t += 0.1
    @show t i
end
2 Likes

If you are an introductory user, then I suggest for now either (1) using Jupyter for exploration, as it is more intuitive; or (2) wrap code with loops in functions if working in the console or top level scripts.

1 Like

Or just use the global keyword if you want to modify a global variable from inside a loop, function or other scope block.

11 Likes

Thanks. I will reread the manual and try to understand why this works.

Thanks. I will try to get Jupyter.

I will reread the manual and try to understand why this works. Thanks !

4 posts were split to a new topic: Installing IJulia