Smyčky while

Intermediate Julia

Anthony Markham

Quantitative Developer

Smyčky while – syntaxe

  • Méně časté než smyčka for, ale v některých případech užitečné.
  • Opakuje expression, dokud je condition pravdivá.
  • Často se používá k opakování akce, dokud není splněna podmínka.
while condition
    expression
end
Intermediate Julia

Smyčky while – příklad

  • Opakuje sadu akcí, dokud je podmínka pravdivá
counter = 10
while counter != 0
    print(counter, " ")
    counter = counter - 1
end
10 9 8 7 6 5 4 3 2 1
Intermediate Julia

Smyčky while – příklad první iterace

# First iteration
counter = 10
while counter != 0  # counter = 10 here, so this is true
    print(counter, " ")  # print counter, equal to 10
    counter = counter - 1  # decrease the value of counter by 1
end
10
Intermediate Julia

Smyčky while – příklad druhá iterace

# Second iteration
counter = 10
while counter != 0  # counter now = 9 here, so this is true
    print(counter, " ")  # print counter, equal to 9
    counter = counter - 1  # decrease the value of counter by 1
end
10 9
Intermediate Julia

Smyčky while – příklad třetí iterace

# Third iteration
counter = 10
while counter != 0  # counter now = 8 here, so this is true
    print(counter, " ")  # print counter, equal to 8
    counter = counter - 1  # decrease the value of counter by 1
end
10 9 8
Intermediate Julia

Smyčky while – nekonečná smyčka

  • Co se stane, pokud zapomeneme dekrementovat proměnnou counter?
# Second iteration
counter = 10
while counter != 0  # counter now = 9 here, so this is true
    print(counter, " ")  # print counter, equal to 9
end
10 10 10 10 10 10 10 10 10
Intermediate Julia

Smyčky while – ukončení

  • V prostředí DataCamp nekonečná smyčka způsobí odpojení relace
  • Na lokálním počítači ukončete program Julia pomocí Ctrl + C
Intermediate Julia

Pojďme si procvičit!

Intermediate Julia

Preparing Video For Download...