Pętle while

Julia średnio zaawansowana

Anthony Markham

Quantitative Developer

Pętle while – składnia

  • Rzadziej stosowana niż pętla for, ale przydatna w niektórych przypadkach.
  • Powtarza expression, dopóki condition jest prawdziwy.
  • Często używana do powtarzania akcji do momentu spełnienia warunku.
while condition
    expression
end
Julia średnio zaawansowana

Pętle while – przykład

  • Powtarza zestaw działań, dopóki warunek jest prawdziwy
counter = 10
while counter != 0
    print(counter, " ")
    counter = counter - 1
end
10 9 8 7 6 5 4 3 2 1
Julia średnio zaawansowana

Pętle while – przykład, pierwsza iteracja

# 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
Julia średnio zaawansowana

Pętle while – przykład, druga iteracja

# 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
Julia średnio zaawansowana

Pętle while – przykład, trzecia iteracja

# 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
Julia średnio zaawansowana

Pętle while – pętla nieskończona

  • Co się stanie, jeśli zapomnimy dekrementować zmienną 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
Julia średnio zaawansowana

Pętle while – zakończenie

  • W środowisku DataCamp nieskończona pętla spowoduje rozłączenie sesji
  • Na komputerze lokalnym należy zakończyć program Julia za pomocą Ctrl + C
Julia średnio zaawansowana

Czas na ćwiczenia!

Julia średnio zaawansowana

Preparing Video For Download...