为什么这里没有识别这个变量

时间:2021-03-24 12:27:54

标签: loops variables julia

我正在努力学习 Julia。为什么下面的简单代码没有运行:

chnum = 3
while chnum < 100
    println(chnum)
    chnum = chnum + 2
end 

错误是:

RROR: LoadError: UndefVarError: chnum not defined        <<<<< NOTE THIS.
Stacktrace:
 [1] top-level scope at /home/iuser/testing.jl:4 [inlined]
 [2] top-level scope at ./none:0
 [3] include at ./boot.jl:317 [inlined]
 [4] include_relative(::Module, ::String) at ./loading.jl:1044
 [5] include(::Module, ::String) at ./sysimg.jl:29
 [6] exec_options(::Base.JLOptions) at ./client.jl:266
 [7] _start() at ./client.jl:425
in expression starting at /home/iuser/testing.jl:3

为什么此处无法识别 chnum 变量?

1 个答案:

答案 0 :(得分:1)

这是因为作用域在 Julia 中是如何工作的。该文档在 Scope of Variables 上有一个非常好的页面,特别相关的是 On Soft Scope 部分,它解释了为什么规则是这样的背后的基本原理,并且还提供了一些历史(行为已经改变随着时间的推移,在 Julia 1.5 中,您的代码可以在 REPL 或笔记本中运行)。

在这种情况下,声明:

chnum = 3

声明一个名为 chnum 的全局变量。当 while 循环开始时,会创建一个新的局部(软)作用域,因为没有名为 chnum 的局部变量未定义。

可以通过声明 chnum global 来防止错误:

chnum = 3
while chnum < 100
    global chnum
    println(chnum)
    chnum = chnum + 2
end

或者将整个事物包装在一个引入局部作用域的结构中:

function print_stuff()
    chnum = 3
    while chnum < 100
        println(chnum)
        chnum = chnum + 2
    end
end
print_stuff()
相关问题