Function variable scope in IJulia Jupyter notebook

I’m using IJulia Jupyter notebook with Julia 1.3.1
Say I define the following function:

function r(x)
    @show b
    @show a
    a = 1+x+b
    return a
end

And if I run the code below:

a = 5
b = 4
r(1)

I will get the output with an error:

b = 4
UndefVarError: a not defined

Could you please explain why @show b works while @show a doesn’t?

Thank you!

Since a is assigned in the code of the function, it is assumed to be a local variable, different from the outer local variable. On the other hand, b is used but never defined inside the function, so it is taken from the outer scope.

Details (for your version) here:
https://docs.julialang.org/en/v1.3/manual/variables-and-scoping/

2 Likes

Thank you!