Variable which disappear in a for

Hey everyone !
First of all, i would like to thank everyone of this community for the help you give to beginners like me.
Actually, i have a problem about a variable which disappear when i enter a for loop.
Does anyone has an idea why ?

The following code :

a = 0

for i in 0:0.1:pi/2

    a = a + 1;

    θ[1] = i;

end 

LoadError: UndefVarError: a not defined

Kind Regards

see here:

1 Like

Julia has different rules for scoping than what you are used to. See the docs here.

Solution 1: Decalre a global in the loop

a = 0
for i in 1:5
    global a
    a += 1
end

Solution 2: Use a let block

let a = 0
    for i in 1:5
        a += 1
    end
    a
end

Solution 3: Use a function

function foo()
    a = 0
    for i in 1:5
        a += 1
    end
    a
end

In general, solution 3 is the best. You should strive to put all your code in functions. At the REPL, in interactive use, the for loop variable behavior is the same as in a function. This is for convenience only, and scripts in global scope don’t have the same behavior.

6 Likes

If you stick in Jupyter or using the shift-enter in vscode, or in the REPL, things will behave as you are expecting. This is only an issue if you are running them in .jl files. For beginners, it is generally better to start with interactive usage in Jupyter/etc… Then, by the time you want to put loops in files, you will always want them in functions (for a variety of reasons, including performance). If you do this, you will never see this issue again.

2 Likes

In the last case, if you gonna use a file for a simple script, I would suggest developing the habit of putting the whole script inside a main function and calling it.

function main()
    # all code that was directly in global scope  
end
main()
2 Likes

Also note that if you update to Julia 1.5 or above then your example will work at the REPL as intended (except that you have not defined θ in the code you provided).

3 Likes

This + heavy use of Infiltrator.jl and Exfiltrator.jl is the key to doing data analysis in julia imo.

2 Likes