Why isn't `i` defined inside this while?

would you please help me why i cant be known inside this while as following in julia v1+?

W=([1.0825998948767477 9.448347129060197 972.5335271289529; 165.861582812015 4.563134610834678 1.0293311999771995], 0)
i=1;
k=size(W[1],2);
while i < k
    if ((abs(round(W[1][1,i],digits=6)-round(W[1][1,i+1],digits=6))>2) && (abs(round(W[1][2,i],digits=6)-round(W[1][2,i+1],digits=6))>2))
        p=[(W[1][:,i],W[1][:,i+1],"T",pq[4])];
        PQ=[PQ;p];
    end
    if ~(i==1)
        if ((W[1][:,i],1) != (W[1][:,i+1],1))
            list=[(W[1][:,i],0)];
        end
        List=[List;list];
    end
    i=i+1;
end

this error happened

UndefVarError: i not defined
top-level scope at untitled-867f699d493f5b9bf0774f2429eafd0e:5
include_string(::Function, ::Module, ::String, ::String) at loading.jl:1088

Thanks indeed.

Loops introduce a new local scope.

Use functions to encapsulate code and to allow for more optimizations and faster code.

2 Likes

In Julia 1.5 this will work in the REPL and print

ā”Œ Warning: Assignment to `i` in soft scope is ambiguous because a global variable by
 the same name exists: `i` will be treated as a new local. Disambiguate by using `local i`
 to suppress this warning or `global i` to assign to the existing global variable.

when running it as a file.

4 Likes

Thanks very much :slightly_smiling_face:

Thank you :cherry_blossom:. yes it is. Iā€™m converting it to a function.