Julia behavior differs across editors

Dear all,
I’m following the most recent Intro to Julia video and I had problems replicating some of the loops in Juno. The example code is this one:

n = 0
while n <10
n += 1
println(n)
end
n

UndefVarError: n not defined
top-level scope at untitled-d413ed921805dfc69b16f1e54a5a5c4e:64 [inlined]
top-level scope at none:0
include_string(::Module, ::String, ::String) at loading.jl:1008
include_string(::Module, ::String, ::String, ::Int64) at eval.jl:30
(::getfield(Atom, Symbol(“##114#119”)){String,Int64,String})() at eval.jl:94
withpath(::getfield(Atom, Symbol(“##114#119”)){String,Int64,String}, ::Nothing) at utils.jl:30
withpath at eval.jl:46 [inlined]
#113 at eval.jl:93 [inlined]
with_logstate(::getfield(Atom, Symbol(“##113#118”)){String,Int64,String}, ::Base.CoreLogging.LogState) at logging.jl:395
with_logger at logging.jl:491 [inlined]
#112 at eval.jl:92 [inlined]
hideprompt(::getfield(Atom, Symbol(“##112#117”)){String,Int64,String}) at repl.jl:85
macro expansion at eval.jl:91 [inlined]
(::getfield(Atom, Symbol(“##111#116”)))(::Dict{String,Any}) at eval.jl:86
handlemsg(::Dict{String,Any}, ::Dict{String,Any}) at comm.jl:164
(::getfield(Atom, Symbol(“##19#21”)){Array{Any,1}})() at task.jl:259

But when I use Jupyter, it goes like this:

n = 0
while n <10
n += 1
println(n)
end
n

​1
2
3
4
5
6
7
8
9
10

10

Why does this happen? Thank you in advance.

Because of default to soft global scope by stevengj · Pull Request #720 · JuliaLang/IJulia.jl · GitHub. This is a bit of a sore point of Julia 1.0. If you’re interested, search for “scope” in this forum, make yourself a cup of tea or grab a beer and enjoy the read.

PS: please quote your code when posting PSA: how to quote code with backticks

2 Likes

Thank you for your answer, will do both.