Scope when using the if-else-end

This program fails. Knowing that “if… does not introduce a new scope”, how to repair it?

a = 1
while a >0
  local a
  print("n, 1=next  "); a =  parse(Int, readline() )
  if a == 1
    u = u + 1     # this line #7 is failing...
  else
    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:

julia> include("prime-other.jl")
n, 1=next  4
4 8
n, 1=next  5
5 10
n, 1=next  1
ERROR: LoadError: UndefVarError: `u` not defined
Stacktrace:
 [1] top-level scope
   @ C:\Users\worker3\Desktop\primality\try-other.jl:7
 [2] include(fname::String)
   @ Base.MainInclude .\client.jl:478
 [3] top-level scope
   @ REPL[2]:1
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 let block

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 a.

2 Likes

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 ('). :slight_smile:

function looks_better()
   @show "looks better, doesn't it?"
end

(I edited the post to fix the quotes.)

1 Like

Looks like you accidentally described backticks (`) as single quotes (') :smiley:

To be clear, triple backtick fences create code blocks.

2 Likes