While 迴圈

Julia 中級

Anthony Markham

Quantitative Developer

While 迴圈:語法

  • for 迴圈少見,但在部分情境很實用。
  • condition 為 true 時,重複執行 expression
  • 常用來重複動作直到滿足某個條件。
while condition
    expression
end
Julia 中級

While 迴圈:範例

  • 重複一組動作直到條件為 true
counter = 10
while counter != 0
    print(counter, " ")
    counter = counter - 1
end
10 9 8 7 6 5 4 3 2 1
Julia 中級

While 迴圈:第一次迭代

# 第一次迭代
counter = 10
while counter != 0  # 這裡 counter = 10,所以為 true
    print(counter, " ")  # 列印 counter,等於 10
    counter = counter - 1  # 將 counter 減 1
end
10
Julia 中級

While 迴圈:第二次迭代

# 第二次迭代
counter = 10
while counter != 0  # 現在 counter = 9,所以為 true
    print(counter, " ")  # 列印 counter,等於 9
    counter = counter - 1  # 將 counter 減 1
end
10 9
Julia 中級

While 迴圈:第三次迭代

# 第三次迭代
counter = 10
while counter != 0  # 現在 counter = 8,所以為 true
    print(counter, " ")  # 列印 counter,等於 8
    counter = counter - 1  # 將 counter 減 1
end
10 9 8
Julia 中級

While 迴圈:無限迴圈

  • 如果忘了遞減 counter 變數,會發生什麼事?
# 第二次迭代
counter = 10
while counter != 0  # 現在 counter = 9,所以為 true
    print(counter, " ")  # 列印 counter,等於 9
end
10 10 10 10 10 10 10 10 10
Julia 中級

While 迴圈:終止方式

  • 在 DataCamp 環境中,無限迴圈會導致工作階段中斷。
  • 在本機電腦上,可用 Ctrl + C 終止 Julia 程式。
Julia 中級

一起來練習吧!

Julia 中級

Preparing Video For Download...