Undefined variable error

I tried to run the while loop example (from Visual Studio Code on Windows 10):

n = 0
while n < 10
n += 1

and got the following error:

Warning: Assignment to n in soft scope is ambiguous because a global variable by the same name exists: n will be treated as a new local. Disambiguate by using local n to suppress this warning or global n to assign to the existing global variable.
└ @ c:\wmen\Programming\JuliaProjects\FirstSteps\course2.jl:4
ERROR: LoadError: UndefVarError: n not defined

the examples with dictionaries, tuples, arrays worked fine. Any ideas? Cheers Markus

Did you read the text in the warning message? It tells you the solution.

For more information, this post may help.


If just starting out, I suggest working in jupyter notebooks, where you will find the scoping rules very intuitive.

thanks for the input. It seems you have to put a “global n” declaration in a while loop in order to make it work. A bit strange.

If you ever have to use global, almost certainly you should change the code. Only weird code would ever require it.

Use jupyter to tinker with scripts, where the scoping is completely intuitive, and then put any code with those sorts of loops inside of functions before running in .jl files. You will never see this issue again.

1 Like