This program fails. Knowing that “if… does not introduce a new scope”, how to repair it?
a = 1
while a >0
print("n, 1=next "); a = parse(Int, readline() )
if a == 1
u = u + 1 # this line #7 is failing...
u = a
end # end if
println( u,' ',2*u )
end # end while
When using the REPL with julia 1.9.0 , the input 4 and 5 work ok, the next input, 1, fails.
This is the REPL dump:
n, 1=next 4
n, 1=next 5
n, 1=next 1
ERROR: LoadError: UndefVarError: `u` not defined
 top-level scope
@ Base.MainInclude .\client.jl:478
 top-level scope
in expression starting at C:\Users\worker3\Desktop\primality\try-other.jl:2
I am a beginner. Any help? Any reference to the docs? Thanks
From the docs:
In loops and comprehensions, new variables introduced in their body scopes are freshly allocated for each loop iteration, as if the loop body were surrounded by a
So each iteration’s
u is different, and by the time you try
u = u + 1, the right-hand
u was not assigned. If you want a
u that persists across all iterations, access one from the scope outside
while. If the outer scope is global, you’ll need a
global u declaration to access it in a script, don’t need it in a REPL or notebook.
Also, are you sure you intended the
local a? It’s different from the outer
a=1 that’s getting checked in
while a>0, so that while loop will run forever since you lost the ability to alter the outer
It looks like you tried to mark up your code block with triple double quote characters (") … you probably meant to use triple single quote characters (').
@show "looks better, doesn't it?"
(I edited the post to fix the quotes.)
Looks like you accidentally described backticks (`) as single quotes (')
To be clear, triple backtick fences create code blocks.