Julia 基本语法学习笔记
变量
Julia 中使用 =
符号来赋值。变量名可以包含字母、数字和下划线,但必须以字母开头。变量名是大小写敏感的。
juliaCopy Codex = 2
y = 3
z = x + y
数据类型
Julia 中有许多不同的数据类型,包括数值、布尔型、字符串、数组、元组、字典等等。以下是一些常见的数据类型示例:
juliaCopy Codex = 1.5 # Float64
y = 1 # Int64
z = true # Bool
s = "hello" # String
a = [1, 2, 3] # Array
t = (1, "hello") # Tuple
d = Dict("a"=>1, "b"=>2) # Dictionary
控制流程
在 Julia 中,我们可以使用 if
和 else
来实现条件语句,使用 for
和 while
循环语句。
juliaCopy Codex = 2
if x > 0
println("x is positive")
elseif x == 0
println("x is zero")
else
println("x is negative")
end
for i in 1:10
println(i)
end
i = 1
while i <= 10
println(i)
i += 1
end
函数
函数是 Julia 中的一等公民。我们可以用 function
关键字定义函数,并使用 return
返回值。
juliaCopy Codefunction square(x)
return x^2
end
println(square(2)) # 输出 4
# 可选参数和默认参数
function power(x, n=2)
return x^n
end
println(power(2)) # 输出 4
println(power(2, 3))# 输出 8
# 匿名函数
f = x -> x^2
println(f(3)) # 输出 9
以上是 Julia 的基本语法学习笔记。更多关于 Julia 的内容可以在官方文档中找到:https://docs.julialang.org/en/v1/