Same code different result in let block and begin block

Hi, I have same code in both let block and begin block, but get totally different results,
any suggestion for understand this?

begin
    x = randn(100,10)
    function f()
        x = randn(2,2)
        return 1
    end
    a = f()
    println(size(x))
end
# (100,10)


let
    x = randn(100,10)
    function f()
        x = randn(2,2)
        return 1
    end
    a =  f()
    println(size(x))
end
#(2,2)

why the f() in let block could change the value of x?, they are different scope, I think.

Thanks for your help.

Maybe Scope of Variables · The Julia Language helps you.

1 Like

In the let block the function f captures the x which is in a local scope. But in the begin block x is in global scope so the function creates a new variable unless you tell it global x = ...

3 Likes

Thanks for your help. I read the URL before posting this question, but I used to think that the `x’ in the let and begin blocks were locally scoped.

And @dlakelan pointed out that `x’ in the begin block is globally scoped, now I can understand the difference result in my code.