Help to set properly the scope of a dataframe: want it to be local to a function but not local within each interation of a for-loop inside that function

Hello, I have made the following MWE:

using DataFrames

function Neuquen(df_in::DataFrame)::DataFrame
    for i in 1:2
        println("step $i")
        df_built = append!(df_in, DataFrame(a=[1,2,3], b=[1,2,3], c=[1,2,3]))
        if i==1
            df_local = df_built
        else
            append!(df_local, df_built)
        end
    end
    println("df_local = $df_local")
    return df_local
end

df_in = DataFrame(a=7ones(3), b=8ones(3), c=9ones(3))
df_out = Neuquen(df_in)
println(df_out)

As it is, it gives error when reaching the second step of the loop because it doesn’t recognize the df_local data frame that was defined in the first step. If I declare global df_local at the beginning of the function it works, but I do not want to have that data frame as a global variable. The code also works if I define local df_local but I supposed that this declaration shouldn’t be necessary if I do not have any df_local in the outermost scope, that could introduce ambiguity.
Summing up, as the code is written above, why Julia is not aware in the second step of a variable declared in the first step of a loop?
Thank you very much!

You want the reserved syntax local

julia> function foo()
           for i in 1:5
               if i == 1
                   x = 1
               else
                   x = x + i
               end
               println(x)
           end
       end
foo (generic function with 1 method)

julia> foo()
1
ERROR: UndefVarError: x not defined
Stacktrace:
 [1] foo()
   @ Main ./REPL[6]:6
 [2] top-level scope
   @ REPL[7]:1

julia> function foo()
           local x
           for i in 1:5
               if i == 1
                   x = 1
               else
                   x = x + i
               end
               println(x)
           end
       end
foo (generic function with 1 method)

julia> foo()
1
3
6
10
15
2 Likes

Thanks @pdeffebach. So the syntax local is not only used to solve ambiguities between the scope of a function and the main but also to state that the variable’s scope is not within a for loop ?