What's wrong here, why getting UndefVarError?

Hey there,
I’m new to Julia and have some experiences with Python, but hate its slowness.

To get to know Julia, I wanted to resolve some problems from projecteuler, also to compare the time needed by Python and Julia.

The first problem isn’t that heavy and it needed only 6 lines in Python.
But If I try to write the same algorithm Julia (using Atom), I get the following error:

> UndefVarError: var not defined

And I can’t figure out, where the mistake could be.
This is the code I already have, and in theory, this should work, shouldn’t it?

#!/usr/bin/env julia
var = 0
for i = 1:1000
  if i % 3 == 0 || i % 5 == 0
    var += i
  end
end
println(var)

Why is my variable var undefinded, if I define it in first place?
This seems for me quite illogical.

What’s my mistake, and what’s the actual reason that my version doesn’t work?

Best Wishes!
TimeMen

This works:

julia> for i = 1:1000
         if i % 3 == 0 || i % 5 == 0
           global var += i
         end
       end

This is the global scope issue, see Another possible solution to the global scope debacle.

Also note that for speed, you need to do your computations inside a function. Where that loop will work just fine (without the global).

1 Like