Циклы с while
Повторяйте действия, пока условие не изменится.
«Циклы с while» — бесплатный урок Mojo Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Mojo Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Mojo Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Repeat Until Done
Sometimes you must run code again and again. A while loop repeats its block as long as a condition stays true. 🔁
The while Shape
Write while, a condition, a colon, then an indented block. Mojo rechecks the condition before every pass through the body.
while count < 3:
print(count)Change the Condition Inside
The body must eventually make the condition false. Usually you update a counter so the loop progresses toward stopping.
var count = 0
while count < 3:
print(count)
count += 1Watch for Infinite Loops
If the condition never turns false, the loop runs forever. An infinite loop usually means you forgot to update the variable it checks.
Condition Checked First
Mojo tests the condition before the first pass. If it is already false, the body never runs even once.
while False:
print("never shown")Accumulate a Result
Loops shine when building up a value. Keep a running total in a variable and add to it on each pass.
var total = 0
var i = 1
while i <= 5:
total += i
i += 1Counting Down
A while loop can move in any direction. Start high and decrement each pass to count down toward a stopping point.
var n = 3
while n > 0:
print(n)
n -= 1Loop on a Flag
The condition need not be a number. A boolean flag works too, letting other logic decide when the loop should end.
var running = True
while running:
running = step()Combine with if
Inside a while body you can branch with if. This lets each pass make its own decision based on the current state.
while i < 10:
if i % 2 == 0:
print(i)
i += 1Pick while When Count Is Unknown
Use while when you do not know in advance how many passes you need, such as reading until a value appears.
Update Before You Forget
A reliable habit: put the update step right where the loop must make progress, so the condition can truly change each pass.
Quick Check
You wrote a while loop but it runs forever and never stops. What is the most likely cause?
Recap
A while loop repeats while its condition is true, checking before each pass. Update the condition inside the body to avoid looping forever. 🎯
Часто задаваемые вопросы
Урок «Циклы с while» бесплатный?
Да — полный текст урока «Циклы с while» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Mojo Academy, подпишись на CoddyKit PRO. Курс Mojo Academy содержит 4 уроков всего.
Чему я научусь в уроке «Циклы с while»?
Повторяйте действия, пока условие не изменится. Ты практикуешь Mojo Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Mojo Academy?
Предыдущий опыт не требуется. Mojo Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Циклы с while»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Mojo Academy?
Да. Каждый урок Mojo Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.