Julia编程08:控制流Control Flow

2024-05-25  本文已影响0人  生信探索

Julia provides a variety of control flow constructs:

Compound Expressions: begin and ;.

Conditional Evaluation: if-elseif-else and ?: (ternary operator).

Short-Circuit Evaluation: logical operators && (“and”) and || (“or”), and also chained comparisons.

Repeated Evaluation: Loops: while and for.

复合表达式 Compound Expressions

可以使用begin...end 或者;,z为最后一个表达式的结果

z = begin

    x = 1

    y = 2

    x + y

end

z = (x = 1; y = 2; x + y)

begin x = 1; y = 2; x + y end

条件语句Conditional Evaluation

if 后边只能是布尔值即(true 或 false),和Python不同可以放None表示False

if x < y

    println("x is less than y")

elseif x > y

    println("x is greater than y")

else

    println("x is equal to y")

end

三元运算符ternary operator

注意R的ifelse是向量化的,也就是说test可以是多个布尔值

# python

a if test else b #如果test为真则返回a,否则返回b #

# R

ifelse(test,a,b) # 向量化

# Julia

test ? a:b

短路运算Short-Circuit Evaluation

可以替换if判断

function fact(n::Int)

    if n<0:

        println("n must be non-negative")

    end

    if n==0:

        return 1

    end

    n * fact(n-1)

end

function fact(n::Int)

    n >= 0 || println("n must be non-negative")

    n == 0 && return 1

    n * fact(n-1)

end

循环Repeated Evaluation: Loops

while循环

i = 1;

while i <= 5

    println(i)

    global i += 1

end

for循环

for i = 1:5

    println(i)

end

break

结果为1:5。如果j≥5就直接跳出循环

for j = 1:1000

    println(j)

    if j >= 5

        break

    end

end

continue

结果为3,6,9。如果i不是3的整倍数,那么就不运行println(i),直接进入下一次循环

for i = 1:10

    if i % 3 != 0

        continue

    end

    println(i)

end

嵌套for循环nested for

第一种相当于i和j的笛卡尔积,第二种是对应位置组合,如果位数不相同,那么只保留短的。

for i = 1:3, j = 4:7

    println((i, j))

end

# (1, 4)

# (1, 5)

# (1, 6)

# (1, 7)

# (2, 4)

# (2, 5)

# (2, 6)

# (2, 7)

# (3, 4)

# (3, 5)

# (3, 6)

# (3, 7)

for (j, k) in zip([1 2 3], [4 5 6 7])

    println((j,k))

end

# (1, 4)

# (2, 5)

# (3, 6)

上一篇下一篇

猜你喜欢

热点阅读