Is there anybody know why this kind of simple code cannot be run?

function test_reason()
    for i = 1:10
        if i == 1
            x = 1
        else 
            x = x+1
        end
    end

end

test_reason()

It seems that it has some scope problem but it’s strange that I have alread define a fucntion for it.

See the loop scoping rules, in particular this part:

[N]ew variables introduced in their body scopes are freshly allocated for each loop iteration

You need to define x outside the loop if you want it to persist beyond each loop iteration.

julia> function test_reason()
           local x
           for i = 1:10
               if i == 1
                   x = 1
               else
                   x = x+1
               end
           end
           return x
       end
test_reason (generic function with 1 method)

julia> test_reason()
10
5 Likes

That’s helpful.
Thank you.

Or

function test_reason()
           x = 1
           for i = 1:10
               if i > 1
                   x = x+1
               end
           end
           return x
       end

I think I gave a similar question a good answer in the past: I thought I understood "pass-by-sharing" in Julia until I found this - #19 by Henrique_Becker.

Even simpler:

function test_reason()
    x = 0
    for i = 1:10
        x = x+1
     end
     return x
end

Or (though I expect this is just due to an overly M MWE):

test_reason() = 10