Variable scope in IJulia Jupyter notebook

I’m using Jupyter notebook by doing:

using IJulia
notebook()

Now, if I try the following code:

a = 1
for i = 1:2
    a = a+1
end

and the value of a would be 3. Isn’t it supposed to be an error as for loop can not modify the value of the global variable a?

Indeed if I run the code in Julia directly, instead of in Jupyter, I will get the error:" ERROR: UndefVarError: a not defined".

I don’t understand why the responds are different. Is there anything I am missing with the Jupyter notebook?

Thank you!

IJulia.jl uses a plugin called SoftGlobalScope.jl to provide this behaviour. However, Julia’s REPL will start providing this behaviour as well starting in Julia 1.5. Note, this will not apply to scripts or packages, only the REPL.

3 Likes

Thank you! Do IJulia and Julia have other different behaviors that might cause confusions? Or is there a way to detect such differences?

Since IJulia doesn’t give an error in my example, I can’t realize my code is wrong until I run it in Julia.

I always develop my codes in IJulia, if there are such different behaviors I don’t realize, I might be writing codes that will not work in Julia.

1 Like