Из этого материала вы узнаете, что такое циклы while, как они могут становиться бесконечными, как использовать инструкцию else
в цикле while и как прерывать исполнение цикла.
Как и другие языки программирования Python включает несколько инструкций для управления потоком. Одна из таких — if else. Еще одна — циклы. Циклы используются в тех случаях, когда нужно повторить блок кода определенное количество раз.
Что такое цикл while в Python?
Цикл while используется в Python для неоднократного исполнения определенной инструкции до тех пор, пока заданное условие остается истинным. Этот цикл позволяет программе перебирать блок кода.
while test_expression:
body of while
Сначала программа оценивает условие цикла while. Если оно истинное, начинается цикл, и тело while
исполняется. Тело будет исполняться до тех пор, пока условие остается истинным. Если оно становится ложным, программа выходит из цикла и прекращает исполнение тела.
Рассмотрим пример, чтобы лучше понять.
a = 1
while a < 10:
print('Цикл выполнился', a, 'раз(а)')
a = a+1
print('Цикл окончен')
Вывод:
Цикл выполнился 1 раз
Цикл выполнился 2 раз
Цикл выполнился 3 раз
Цикл выполнился 4 раз
Цикл выполнился 5 раз
Цикл выполнился 6 раз
Цикл выполнился 7 раз
Цикл выполнился 8 раз
Цикл выполнился 9 раз
Цикл окончен
Бесконечный цикл while в Python
Бесконечный цикл while — это цикл, в котором условие никогда не становится ложным. Это значит, что тело исполняется снова и снова, а цикл никогда не заканчивается.
Следующий пример — бесконечный цикл:
a = 1
while a==1:
b = input('Как тебя зовут?')
print('Привет', b, ', Добро пожаловать')
Если запустить этот код, то программа войдет в бесконечный цикл и будет снова и снова спрашивать имена. Цикл не остановится до тех пор, пока не нажать Ctrl + C
.
Else в цикле while
В Python с циклами while также можно использовать инструкцию else
. В этом случае блок в else
исполняется, когда условие цикла становится ложным.
a = 1
while a < 5:
print('условие верно')
a = a + 1
else:
print('условие неверно')
Этот пример демонстрирует принцип работы else
в цикле while.
Вывод:
условие верно
условие верно
условие верно
условие верно
условие неверно
Программа исполняет код цикла while до тех, пока условие истинно, то есть пока значение a
меньше 5. Поскольку начальное значение a
равно 1, а с каждым циклом оно увеличивается на 1, условие станет ложным, когда программа доберется до четвертой итерации — в этот момент значение a
изменится с 4 до 5. Программа проверит условие еще раз, убедится, что оно ложно и исполнит блок else
, отобразив «условие неверно».
Прерывания цикла while в Python
В Python есть два ключевых слова, с помощью которых можно преждевременно остановить итерацию цикла.
- Break — ключевое слово
break
прерывает цикл и передает управление в конец циклаa = 1 while a < 5: a += 1 if a == 3: break print(a) # 2
- Continue — ключевое слово
continue
прерывает текущую итерацию и передает управление в начало цикла, после чего условие снова проверяется. Если оно истинно, исполняется следующая итерация.
a = 1
while a < 5:
a += 1
if a == 3:
continue
print(a) # 2, 4, 5
Обучение с трудоустройством
В прошлой статье мы изучали цикл for – он
используется в тех случаях, когда заранее известно количество итераций,
совершаемых в цикле. Число исполнений цикла for определяется функцией range()
или размером коллекции. Если диапазон значений не
известен заранее, необходимо использовать другой цикл – while: он выполняется, пока не наступит
определенное событие (или не выполнится необходимое условие). По этой причине
цикл while называют условным. Вот пример простейшего цикла while – он выполняется, пока пользователь
не введет 0
:
n = int(input())
while n != 0:
print(n + 5)
n = int(input())
Цикл while также часто называют бесконечным, поскольку он может
выполняться до тех пор, пока пользователь не остановит его нажатием
определенной клавиши. Бесконечные циклы можно создавать намеренно – для
выполнения фонового скрипта, игры, прикладной программы. Но иногда цикл while может
стать бесконечным из-за ошибки. Например, если в приведенном выше коде не
указать ввод новой переменной n = int(input())
в теле цикла, while будет
бесконечно выводить одно и то же значение, пока пользователь не остановит выполнение программы нажатием Ctrl + C.
Управление бесконечным циклом while в Питоне
Самый простой способ управления бесконечным циклом –
использование оператора break
.
В приведенном ниже коде список lst
генерируется случайным образом, и до начала цикла его длина
неизвестна. Однако выполнение цикла можно оставить, как только список опустеет
в результате многократного выполнения операции pop()
:
import random
lst = [i for i in range(random.randint(5, 500))]
while True:
if not lst:
break
print(lst.pop())
Если выполнение цикла не остановить сразу же, как только список опустеет, появится ошибка:
IndexError: pop from empty list
Оператор break
также помогает сократить количество итераций и прекратить выполнение программы, как только нужное решение найдено. Например, таким образом можно найти наименьший делитель числа n, отличный от 1:
n = int(input())
i = 2
while True:
if n % i == 0:
break
i += 1
print(i)
Помимо break
,
управлять бесконечным циклом можно с помощью флагов (сигнальных меток). В
приведенном ниже примере программа бесконечно запрашивает у пользователя ввод
любого слова, пока пользователь не введет exit
. Это событие меняет статус цикла на False
, и работа программы завершается:
text = 'Введите любое слово: '
text += 'nИли введите exit для выхода: '
active = True
while active:
message = input(text)
if message == 'exit':
active = False
else:
print(message)
Пропуск итераций в цикле while
Оператор continue
можно использовать для пропуска операций, если элементы не соответствуют
заданным критериям. Этот код работает, пока не будет сформирован список из 5
элементов – при этом в список не включаются числа в диапазоне между 90 и 120, а
также число 50:
sp = []
while len(sp) < 5:
num = int(input())
if num == 50 or 90 <= num <= 120:
continue
sp.append(num)
print(sp)
Если пользователь введет набор цифр 45 50 121 119
, в список будут добавлены только числа, соответствующие
95 105 3 4 7
критериям:
[45, 121, 3, 4, 7]
Особенности цикла while
1. В цикле while можно использовать опциональный параметр else
. В этом примере процедура pop()
выполняется, пока
список не опустеет, после чего выводится сообщение Список пуст
:
import random
lst = [i for i in range(random.randint(5, 500))]
while len(lst) > 1:
print(lst.pop())
else:
print('Список пуст')
2. В цикле while можно использовать любое количество условий и условных
операторов and
, or,
иnot
:
n = int(input())
while True:
if n == 0:
break
elif n > 50 or n <= -50:
break
elif n % 2 == 0:
break
print(n / 5)
n = int(input())
3. Цикл while может быть вложенным. Этот код выводит простые числа из
диапазона от 2 до 100:
i = 2
while(i < 100):
j = 2
while j <= i / j:
if not i % j:
break
j = j + 1
if j > i / j:
print(f'{i} - простое число')
i = i + 1
4. В качестве вложенных циклов while могут включать в себя циклы for. Этот код, к примеру,
будет бесконечно печатать цифры в диапазоне от 0 до 5:
while True:
for i in range(5):
print(i)
5. Любой цикл for можно заменить циклом while, но обратное возможно только в том случае, когда количество итераций можно определить до начала цикла. К примеру, эти циклы while и for равнозначны – оба печатают цифры от 0 до 9:
i = 0
while i < 10:
print(i)
i += 1
for i in range(10):
print(i)
А этот цикл while заменить циклом for невозможно – программа будет бесконечно
возводить в квадрат все введенные пользователем числа, пока не получит 0
:
n = int(input())
while True:
if n == 0:
break
print(n ** 2)
n = int(input())
Практика
Задание 1
Напишите программу, которая принимает на вход целые числа и
вычисляет их сумму, пока пользователь не введет 0.
Пример ввода:
4
5
6
0
Вывод:
15
Решение:
summa = 0
while True:
n = int(input())
summa += n
if n == 0:
break
print(summa)
Задание 2
Напишите программу, которая получает от пользователя число n > 100, и вычисляет (без
использования методов строк) произведение цифр, из которых n состоит.
Пример ввода:
335
Вывод:
45
Решение:
n = int(input())
prod = 1
while n:
prod *= n % 10
n //= 10
print(prod)
Задание 3
Напишите программу, которая получает на вход два числа a и b, и находит наименьшее число c, которое без остатка
делится на a и b.
Пример ввода:
7
12
Вывод:
84
Решение:
a, b = int(input()), int(input())
c = a
while c % b:
c += a
print(c)
Задание 4
Напишите программу, которая составляет строку из полученных
от пользователя слов, пока длина строки не достигнет 50 символов. Слова,
начинающиеся с гласных, в строку не включаются.
Пример ввода:
о
бойся
Бармаглота
сын
он
так
свиреп
и
дик
а
в глуще
рымит
Вывод:
бойся Бармаглота сын так свиреп дик в глуще рымит
Решение:
st = ''
while len(st) < 50:
word = input()
if word[0] in 'аиеёоуыэюя':
continue
st += ' ' + word
print(st)
Задание 5
Напишите программу для конвертации числа из десятичного системы
в двоичную без использования функции bin()
.
Пример ввода:
25
Вывод:
11001
Решение:
n = int(input())
result = ''
while n > 0:
result = str(n % 2) + result
n = n // 2
print(result)
Задание 6
Напишите программу, которая получает на вход число и без
использования строковых методов переставляет цифры в обратном порядке.
Пример ввода:
176435
Вывод:
534671
Решение:
n = int(input())
rev = 0
while n!= 0:
r = n % 10
rev = rev * 10 + r
n = n // 10
print(rev)
Задание 7
Напишите программу для вычисления факториала числа n без использования функции math.factorial()
.
Пример ввода:
7
Вывод:
5040
Решение:
n = int(input())
fact = 1
while n > 1:
fact *= n
n -= 1
print(fact)
Задание 8
Напишите программу, которая получает от пользователя число n и
определяет, является ли оно простым, или у него есть делители, кроме 1 и самого
себя.
Пример ввода:
60
Вывод:
60 делится на 2
60 делится на 3
60 делится на 4
60 делится на 5
60 делится на 6
60 делится на 10
60 делится на 12
60 делится на 15
60 делится на 20
60 делится на 30
Таким образом, 60 не является простым числом
Решение:
n = int(input())
flag = False
i = 2
while i < n:
if n % i ==0:
flag = True
print(f'{n} делится на {i}')
i += 1
if flag:
print(f'Таким образом, {n} не является простым числом')
else:
print(f'{n} - простое число')
Задание 9
Напишите программу, использующую вложенный цикл while для вывода треугольника
размером n x n х n, состоящего из символов*
.
Пример ввода:
6
Вывод:
*
**
***
****
*****
******
Решение:
n = int(input())
i, j = 0, 0
while i < n:
while j <= i:
print('*', end='')
j += 1
j = 0
i += 1
print('')
Задание 10
Напишите программу для запоминания английских названий месяцев:
1. Русские названия месяцев выводятся в случайном порядке с
помощью метода random.shuffle()
.
2. Пользователь получает три попытки для написания правильного
названия на английском.
3. После трех неверных попыток программа переходит к другому
слову.
Пример ввода:
Месяц март по-английски называется: march
Месяц январь по-английски называется: January
Месяц август по-английски называется: august
Месяц май по-английски называется: may
Месяц апрель по-английски называется: aprile
Неверно! Осталось попыток: 2
Месяц апрель по-английски называется: aprill
Неверно! Осталось попыток: 1
Месяц апрель по-английски называется: appril
Неверно! Осталось попыток: 0
Попытки исчерпаны!
Месяц июль по-английски называется: july
Месяц сентябрь по-английски называется: september
Месяц июнь по-английски называется: june
Месяц октябрь по-английски называется: october
Месяц ноябрь по-английски называется: november
Месяц декабрь по-английски называется: december
Месяц февраль по-английски называется: february
Вывод:
Конец игры
Количество правильных ответов: 11
Число ошибок: 3
Решение:
import random
correct, wrong, attempts = 0, 0, 3
months = {'январь': 'January', 'февраль': 'February', 'март': 'March',
'апрель': 'April', 'май': 'May', 'июнь': 'June',
'июль': 'July', 'август': 'August', 'сентябрь': 'September',
'октябрь': 'October', 'ноябрь': 'November', 'декабрь': 'December'}
rand_keys = list(months.keys())
random.shuffle(rand_keys)
for key in rand_keys:
counter = 0
while counter < attempts:
spelling = input(f'Месяц {key} по-английски называется: ')
if spelling.title() == months[key]:
correct += 1
break
else:
counter += 1
wrong += 1
print(f'Неверно! Осталось попыток: {attempts - counter}')
else:
print(f'Попытки исчерпаны!')
print('Конец игры')
print(f'Количество правильных ответов: {correct}')
print(f'Число ошибок: {wrong}')
Подведем итоги
Цикл while используют в случаях, когда число итераций невозможно
оценить заранее. Во всех остальных случаях лучше применять цикл for. Чтобы цикл while случайно
не превратился в бесконечный, стоит продумать все события и условия, которые
должны приводить к своевременному прерыванию программы.
В следующей статье приступим к изучению функций.
***
Содержание самоучителя
- Особенности, сферы применения, установка, онлайн IDE
- Все, что нужно для изучения Python с нуля – книги, сайты, каналы и курсы
- Типы данных: преобразование и базовые операции
- Методы работы со строками
- Методы работы со списками и списковыми включениями
- Методы работы со словарями и генераторами словарей
- Методы работы с кортежами
- Методы работы со множествами
- Особенности цикла for
- Условный цикл while
- Функции с позиционными и именованными аргументами
- Анонимные функции
- Рекурсивные функции
- Функции высшего порядка, замыкания и декораторы
- Методы работы с файлами и файловой системой
- Регулярные выражения
Содержание:развернуть
- Немного информатики
- Синтаксис цикла while
- Несколько примеров использования цикла while
- break и continue
- else
- while true или бесконечный цикл
- Best practice
-
Цикл while в одну строку
-
Вложенные циклы
-
Как выйти с помощью break из двух циклов
Использование циклов предоставляет программисту возможность многократного исполнения определенного участка кода. Это один из основных рабочих инструментов любого разработчика, и практически ни одна из существующих программ не обходится без него.
Циклы в языке Python представлены двумя основными конструкциями: while
и for
. Цикл while
считается универсальным, в то время как for
нужен для обхода последовательности поэлементно. Более подробную информацию о цикле for
вы можете прочитать здесь.
Так или иначе, обе конструкции одинаково применимы и являются важнейшими элементами любого высокоуровневого языка, в том числе и языка Python.
Немного информатики
Как было отмечено выше,
Цикл — это управляющая конструкция, которая раз за разом выполняет серию команд (тело цикла) до тех пор, пока условие для выполнения является истинным.
Напишем на псевдокоде классическую схему:
повторять, пока условие
начало цикла
последовательность инструкций
конец цикла
Конструкция начинает свою работу с проверки условия, и, если оно истинно, запускается цикл. На каждой новой итерации (единичный проход по циклу) условие продолжения проверяется вновь. Таким образом, последовательность инструкций будет исполняться до тех пор, пока это условие, наконец, не окажется ложным.
Циклы, как механизм программирования, нужны, главным образом, для упрощения написания кода. Вполне очевидно, что создавать программу, выполняющую определённую операцию для каждой точки 4К дисплея в отсутствии циклов — это вручную повторять описание нужной команды 4096*2160 раз. 🤔 Много? Безусловно.
Применение в этой задаче всего одного цикла позволит сократить длину кода, как минимум, на 6 порядков. А если представить, что ту же самую программу нужно переписать для 8К монитора, то, вместо изменения всего одной инструкции в счетчике цикла, вам придётся дописывать ещё пару десятков миллионов строк кода, что является попросту недопустимым по своей величине и трудозатратам объёмом.
Польза циклов ясна и очевидна. Обладая мощной выразительностью и ёмкой натурой, они, без сомнений, являются одним из фундаментальных конструктов высокоуровневого программирования. Каждому разработчику необходимо знать и понимать принципы их работы.
Синтаксис цикла while
В самом простом случае, цикл while
в python очень похож по своей структуре на условную конструкцию с if
:
import time
a = 1
if a == 1:
print("I'm the condition")
while a == 1:
print("I'm the loop")
time.sleep(1)
И в том и в другом случае, блок кода внутри (инструкция print(‘…’)
) будет исполнен тогда и только тогда, когда условие (a == 1)
будет иметь значение True
. Вот только в конструкции с if
, при успешной проверке, вывод на экран будет выполнен всего один раз, а в случае с while
фраза «I’m the loop» будет печататься бесконечно.
Такое явление называется бесконечным циклом. У них есть свои определенные смысл и польза, но их мы разберём чуть позже, поскольку чаще всего цикл всё-таки должен как-то заканчиваться. И вполне логично, что для его завершения нужно произвести определенные манипуляции с условием.
Переменная a
, в примере выше, называется управляющей (или счетчик). При помощи таких переменных можно контролировать момент выхода из цикла. Для этого их следует сравнить с каким-либо значением.
count = 1 # фиксируем начальное значение
while count <= 10: # и конечное (включительно)
print(count, end=' ')
count += 1
# после 9-й итерации в count будет храниться значение 10
# это удовлетворяет условию count <= 10, поэтому на 10-м витке будет выведено число 10
# (как видно, значение счетчика печатается до его инкрементирования)
# после count станет равным 11, а, значит, следующий прогон цикла не состоится, и он будет прерван
# в итоге получаем:
> 1 2 3 4 5 6 7 8 9 10
В Python есть и более сложные, составные условия. Они могут быть сколь угодно длинными, а в их записи используются логические операторы (not
, and
, or
):
dayoff = False
sunrise = 6
sunset = 18
worktime = 12
# пример составного условия
while not dayoff and sunrise <= worktime <= sunset:
if sunset == worktime:
print("Finally it's over!")
else:
print('You have ', sunset - worktime, ' hours to work')
worktime += 1
>
You have 6 hours to work
You have 5 hours to work
You have 4 hours to work
You have 3 hours to work
You have 2 hours to work
You have 1 hours to work
Finally it's over!
Как можно заметить, управляющая переменная вовсе не обязана являться счётчиком. Она может быть просто логической переменной, чье значение изменяется где-то в самом цикле:
num = 0
control = True
while num < 10:
num += 1
# аналогичная запись
num = 0
control = True
while control:
if num == 10:
control = False
num += 1
Стоит иметь в виду, что использование неинициализированной переменной в качестве управляющей цикла обязательно приведёт к возникновению ошибки:
# unknown до этого нигде не была объявлена
while unknown:
print('+')
>
Traceback (most recent call last):
while unknown:
NameError: name 'unknown' is not defined
Несколько примеров использования цикла while
Идея циклов while
проста — требуется определенное количество раз сделать что-то? Заведи счётчик и уменьшай/увеличивай его в теле цикла.
x = 20
y = 30
while x < y:
print(x, end=' ')
x = x + 3
> 20 23 26 29
Своеобразным счётчиком может быть даже строка:
word = "pythonchik"
while word:
print(word, end=" ")
# на каждой итерации убираем символ с конца
word = word[:-1]
> pythonchik pythonchi pythonch pythonc python pytho pyth pyt py p
break и continue
Оператор break
заставляет интерпретатор прервать выполнение цикла и перейти к следующей за ним инструкции:
counter = 0
while True:
if counter == 10:
break
counter += 1
Цикл прервётся после того, как значение счетчика дойдёт до десяти.
Существует похожий оператор под названием continue
, однако он не прекращает выполнение всей конструкции, а прерывает лишь текущую итерацию, переходя затем в начало цикла:
# классический пример вывода одних лишь чётных значений
z = 10
while z:
z -= 1
if z % 2 != 0:
continue
print(z, end=" ")
> 8 6 4 2 0
Эти операторы бывают весьма удобны, однако плохой практикой считается написание кода, который чересчур ими перегружен.
else
В Python-циклах часть else
выполняется лишь тогда, когда цикл отработал, не будучи прерван break
-ом.
В реальной практике, else
в циклах применяется нечасто. Такая конструкция отлично сработает, когда будет необходимо проверить факт выполнения всех итераций цикла.
👉 Пример из практики: проверка доступности всех выбранных узлов сети
Например, обойти все узлы локальной сети и
def print_prime_list(list_of_numbers: list) -> None:
""" функция выведет список чисел,
если каждое из этих чисел является простым """
number_count = len(list_of_numbers) # количество чисел
i = 0
while i < number_count:
x = list_of_numbers[i] // 2
if x != 0 and list_of_numbers[i] % x == 0:
break
i += 1
else:
print(f'{list_of_numbers} - list is prime!')
print_prime_list([11, 100, 199]) # 100 - не простое число
>
print_prime_list([11, 113, 199])
> [11, 113, 199]
В каком-либо другом языке стоило бы завести булеву переменную, в которой хранится результат проверки, но у Python, как всегда, есть способ получше!
while true или бесконечный цикл
В большинстве случаев, бесконечные циклы появляются из-за логических ошибок программиста (например, когда условие цикла while
при любых вариантах равно True
). Поэтому следует внимательно следить за условием, при котором цикл будет завершаться.
Однако вы некоторых случая бесконечный цикл делают намерено:
- Если нужно производить какие-то действия с интервалом, и выходить из цикла лишь в том случае, когда внутри тела «зашито» условие выхода.
Пример: функция, которая возвращаетconnection
базы данных. Если связь с базой данных отсутствует, соединение будет пытаться (в цикле) установиться до тех пор, пока не установится. - Если вы пишете полноценный демон, который продолжительное время висит как процесс в системе и периодически производит какие-то действия. В таком случае остановкой цикла будет прерывание работы программы. Пример: скрипт, который раз в 10 минут «пингует» IP адреса и пишет в лог отчет о доступности этих адресов.
💁♂️ Совет: в бесконечных циклах рекомендуется ставить таймаут выполнения после каждой итерации, иначе вы очень сильно нагрузите CPU
:
import time
while True:
print("Бесконечный цикл")
time.sleep(1)
>
Бесконечный цикл
Бесконечный цикл
Бесконечный цикл
Traceback (most recent call last):
File "main.py", line 5, in <module>
time.sleep(1)
KeyboardInterrupt
Aborted!
Код был прерван комбинацией клавиш ^Ctrl
+ C
. Иначе цикл продолжался бы бесконечно.
Best practice
Цикл while в одну строку
Для составных конструкций (таких, где нужен блок с отступом), можно этот отступ убрать, но только если в блоке используются простые операторы. Отделяются они всё также двоеточием.
Например, записи:
while x < y:
x +=1
# и
while x < y: x += 1
будут считаться эквивалентными, и при чтении второй из них интерпретатор не будет выдавать ошибку.
Вложенные циклы
Вложенные while
циклы встречаются не так часто, как их братья (или сестры) for
, что, однако не мешает им быть полезными. Простой пример — выведем на экран таблицу умножения:
q = 1
while q <= 9:
w = 1
while w <= 9:
print(q * w, end=" ")
w += 1
q += 1
print("")
>
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Нет никаких проблем с использованием вложенных циклов while
, однако стоит иметь в виду, что вложения свыше третьего уровня будут уже практически нечитаемыми для человека.
Как выйти с помощью break из двух циклов
В случае вложенных циклов, оператор break
завершает работу только того цикла, внутри которого он был вызван:
i = 100
j = 200
while i < 105:
while j < 205:
if j == 203:
break
print('J', j)
j += 1
print('I', i)
i += 1
>
J 200
J 201
J 202
# здесь видно, что внутренний цикл прерывается, но внешний продолжает работу
I 100
I 101
I 102
I 103
I 104
В Python не существует конструкций, которая прерывала бы сразу несколько циклов. Но есть как минимум 3 способа, которыми можно реализовать данное поведение:
Способ №1
Используем конструкцию for ... else ...
:
def same_values_exists(list_1: list, list_2: list) -> None:
""" функция выводит на экран
первые совпавшие числа из списков """
for i in list_1:
for j in list_2:
print("compare: ", i, j)
if i == j:
print(f"found {i}")
break
else:
continue
break
same_values_exists([0, 10, -2, 23], [-2, 2])
>
compare: 0 -2
compare: 0 2
compare: 10 -2
compare: 10 2
compare: -2 -2
found -2
Если все итерации вложенного цикла сработают, выполнится else
, который скажет внешнему циклу продолжить выполнение. Если во внутреннем цикле сработает break
, сразу выполнится второй break
.
Способ №2
Через создание дополнительного флага:
def same_values_exists(list_1: list, list_2: list) -> None:
""" функция выводит на экран
первые совпавшие числа из списков """
break_the_loop = False
for i in list_1:
for j in list_2:
print("compare: ", i, j)
if i == j:
print(f"found {i}")
break_the_loop = True
break
if break_the_loop:
break
same_values_exists([0, 10, -2, 23], [-2, 2])
>
compare: 0 -2
compare: 0 2
compare: 10 -2
compare: 10 2
compare: -2 -2
found -2
Внешний цикл был прерван вслед за внутренним. Дело сделано!
Способ №3
Если циклы находятся в функции (как в нашем примере), достаточно просто сделать return
:
def same_values_exists(list_1: list, list_2: list) -> None:
""" функция выводит на экран
первые совпавшие числа из списков """
for i in list_1:
for j in list_2:
print("compare: ", i, j)
if i == j:
print(f"found {i}")
return
same_values_exists([0, 10, -2, 23], [-2, 2])
>
compare: 0 -2
compare: 0 2
compare: 10 -2
compare: 10 2
compare: -2 -2
found -2
—
Welcome! If you want to learn how to work with while loops in Python, then this article is for you.
While loops are very powerful programming structures that you can use in your programs to repeat a sequence of statements.
In this article, you will learn:
- What while loops are.
- What they are used for.
- When they should be used.
- How they work behind the scenes.
- How to write a while loop in Python.
- What infinite loops are and how to interrupt them.
- What
while True
is used for and its general syntax. - How to use a
break
statement to stop a while loop.
You will learn how while loops work behind the scenes with examples, tables, and diagrams.
Are you ready? Let’s begin. 🔅
🔹 Purpose and Use Cases for While Loops
Let’s start with the purpose of while loops. What are they used for?
They are used to repeat a sequence of statements an unknown number of times. This type of loop runs while a given condition is True
and it only stops when the condition becomes False
.
When we write a while loop, we don’t explicitly define how many iterations will be completed, we only write the condition that has to be True
to continue the process and False
to stop it.
💡 Tip: if the while loop condition never evaluates to False
, then we will have an infinite loop, which is a loop that never stops (in theory) without external intervention.
These are some examples of real use cases of while loops:
- User Input: When we ask for user input, we need to check if the value entered is valid. We can’t possibly know in advance how many times the user will enter an invalid input before the program can continue. Therefore, a while loop would be perfect for this scenario.
- Search: searching for an element in a data structure is another perfect use case for a while loop because we can’t know in advance how many iterations will be needed to find the target value. For example, the Binary Search algorithm can be implemented using a while loop.
- Games: In a game, a while loop could be used to keep the main logic of the game running until the player loses or the game ends. We can’t know in advance when this will happen, so this is another perfect scenario for a while loop.
🔸 How While Loops Work
Now that you know what while loops are used for, let’s see their main logic and how they work behind the scenes. Here we have a diagram:
Let’s break this down in more detail:
- The process starts when a while loop is found during the execution of the program.
- The condition is evaluated to check if it’s
True
orFalse
. - If the condition is
True
, the statements that belong to the loop are executed. - The while loop condition is checked again.
- If the condition evaluates to
True
again, the sequence of statements runs again and the process is repeated. - When the condition evaluates to
False
, the loop stops and the program continues beyond the loop.
One of the most important characteristics of while loops is that the variables used in the loop condition are not updated automatically. We have to update their values explicitly with our code to make sure that the loop will eventually stop when the condition evaluates to False
.
🔹 General Syntax of While Loops
Great. Now you know how while loops work, so let’s dive into the code and see how you can write a while loop in Python. This is the basic syntax:
These are the main elements (in order):
- The
while
keyword (followed by a space). - A condition to determine if the loop will continue running or not based on its truth value (
True
orFalse
). - A colon (
:
) at the end of the first line. - The sequence of statements that will be repeated. This block of code is called the «body» of the loop and it has to be indented. If a statement is not indented, it will not be considered part of the loop (please see the diagram below).
💡 Tip: The Python style guide (PEP recommends using 4 spaces per indentation level. Tabs should only be used to remain consistent with code that is already indented with tabs.
Now that you know how while loops work and how to write them in Python, let’s see how they work behind the scenes with some examples.
How a Basic While Loop Works
Here we have a basic while loop that prints the value of i
while i
is less than 8 (i < 8
):
i = 4
while i < 8:
print(i)
i += 1
If we run the code, we see this output:
4
5
6
7
Let’s see what happens behind the scenes when the code runs:
- Iteration 1: initially, the value of
i
is 4, so the conditioni < 8
evaluates toTrue
and the loop starts to run. The value ofi
is printed (4) and this value is incremented by 1. The loop starts again. - Iteration 2: now the value of
i
is 5, so the conditioni < 8
evaluates toTrue
. The body of the loop runs, the value ofi
is printed (5) and this valuei
is incremented by 1. The loop starts again. - Iterations 3 and 4: The same process is repeated for the third and fourth iterations, so the integers 6 and 7 are printed.
- Before starting the fifth iteration, the value of
i
is8
. Now the while loop conditioni < 8
evaluates toFalse
and the loop stops immediately.
💡 Tip: If the while loop condition is False
before starting the first iteration, the while loop will not even start running.
User Input Using a While Loop
Now let’s see an example of a while loop in a program that takes user input. We will the input()
function to ask the user to enter an integer and that integer will only be appended to list if it’s even.
This is the code:
# Define the list
nums = []
# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
# Ask for user input and store it in a variable as an integer.
user_input = int(input("Enter an integer: "))
# If the input is an even number, add it to the list
if user_input % 2 == 0:
nums.append(user_input)
The loop condition is len(nums) < 4
, so the loop will run while the length of the list nums
is strictly less than 4.
Let’s analyze this program line by line:
- We start by defining an empty list and assigning it to a variable called
nums
.
nums = []
- Then, we define a while loop that will run while
len(nums) < 4
.
while len(nums) < 4:
- We ask for user input with the
input()
function and store it in theuser_input
variable.
user_input = int(input("Enter an integer: "))
💡 Tip: We need to convert (cast) the value entered by the user to an integer using the int()
function before assigning it to the variable because the input()
function returns a string (source).
- We check if this value is even or odd.
if user_input % 2 == 0:
- If it’s even, we append it to the
nums
list.
nums.append(user_input)
- Else, if it’s odd, the loop starts again and the condition is checked to determine if the loop should continue or not.
If we run this code with custom user input, we get the following output:
Enter an integer: 3
Enter an integer: 4
Enter an integer: 2
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6
Enter an integer: 3
Enter an integer: 4
This table summarizes what happens behind the scenes when the code runs:
💡 Tip: The initial value of len(nums)
is 0
because the list is initially empty. The last column of the table shows the length of the list at the end of the current iteration. This value is used to check the condition before the next iteration starts.
As you can see in the table, the user enters even integers in the second, third, sixth, and eight iterations and these values are appended to the nums
list.
Before a «ninth» iteration starts, the condition is checked again but now it evaluates to False
because the nums
list has four elements (length 4), so the loop stops.
If we check the value of the nums
list when the process has been completed, we see this:
>>> nums
[4, 2, 6, 4]
Exactly what we expected, the while loop stopped when the condition len(nums) < 4
evaluated to False
.
Now you know how while loops work behind the scenes and you’ve seen some practical examples, so let’s dive into a key element of while loops: the condition.
🔹 Tips for the Condition in While Loops
Before you start working with while loops, you should know that the loop condition plays a central role in the functionality and output of a while loop.
You must be very careful with the comparison operator that you choose because this is a very common source of bugs.
For example, common errors include:
- Using
<
(less than) instead of<=
(less than or equal to) (or vice versa). - Using
>
(greater than) instead of>=
(greater than or equal to) (or vice versa).
This can affect the number of iterations of the loop and even its output.
Let’s see an example:
If we write this while loop with the condition i < 9
:
i = 6
while i < 9:
print(i)
i += 1
We see this output when the code runs:
6
7
8
The loop completes three iterations and it stops when i
is equal to 9
.
This table illustrates what happens behind the scenes when the code runs:
- Before the first iteration of the loop, the value of
i
is 6, so the conditioni < 9
isTrue
and the loop starts running. The value ofi
is printed and then it is incremented by 1. - In the second iteration of the loop, the value of
i
is 7, so the conditioni < 9
isTrue
. The body of the loop runs, the value ofi
is printed, and then it is incremented by 1. - In the third iteration of the loop, the value of
i
is 8, so the conditioni < 9
isTrue
. The body of the loop runs, the value ofi
is printed, and then it is incremented by 1. - The condition is checked again before a fourth iteration starts, but now the value of
i
is 9, soi < 9
isFalse
and the loop stops.
In this case, we used <
as the comparison operator in the condition, but what do you think will happen if we use <=
instead?
i = 6
while i <= 9:
print(i)
i += 1
We see this output:
6
7
8
9
The loop completes one more iteration because now we are using the «less than or equal to» operator <=
, so the condition is still True
when i
is equal to 9
.
This table illustrates what happens behind the scenes:
Four iterations are completed. The condition is checked again before starting a «fifth» iteration. At this point, the value of i
is 10
, so the condition i <= 9
is False
and the loop stops.
🔸 Infinite While Loops
Now you know how while loops work, but what do you think will happen if the while loop condition never evaluates to False
?
What are Infinite While Loops?
Remember that while loops don’t update variables automatically (we are in charge of doing that explicitly with our code). So there is no guarantee that the loop will stop unless we write the necessary code to make the condition False
at some point during the execution of the loop.
If we don’t do this and the condition always evaluates to True
, then we will have an infinite loop, which is a while loop that runs indefinitely (in theory).
Infinite loops are typically the result of a bug, but they can also be caused intentionally when we want to repeat a sequence of statements indefinitely until a break
statement is found.
Let’s see these two types of infinite loops in the examples below.
💡 Tip: A bug is an error in the program that causes incorrect or unexpected results.
Example of Infinite Loop
This is an example of an unintentional infinite loop caused by a bug in the program:
# Define a variable
i = 5
# Run this loop while i is less than 15
while i < 15:
# Print a message
print("Hello, World!")
Analyze this code for a moment.
Don’t you notice something missing in the body of the loop?
That’s right!
The value of the variable i
is never updated (it’s always 5
). Therefore, the condition i < 15
is always True
and the loop never stops.
If we run this code, the output will be an «infinite» sequence of Hello, World!
messages because the body of the loop print("Hello, World!")
will run indefinitely.
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
.
.
.
# Continues indefinitely
To stop the program, we will need to interrupt the loop manually by pressing CTRL + C
.
When we do, we will see a KeyboardInterrupt
error similar to this one:
To fix this loop, we will need to update the value of i
in the body of the loop to make sure that the condition i < 15
will eventually evaluate to False
.
This is one possible solution, incrementing the value of i
by 2 on every iteration:
i = 5
while i < 15:
print("Hello, World!")
# Update the value of i
i += 2
Great. Now you know how to fix infinite loops caused by a bug. You just need to write code to guarantee that the condition will eventually evaluate to False
.
Let’s start diving into intentional infinite loops and how they work.
🔹 How to Make an Infinite Loop with While True
We can generate an infinite loop intentionally using while True
. In this case, the loop will run indefinitely until the process is stopped by external intervention (CTRL + C
) or when a break
statement is found (you will learn more about break
in just a moment).
This is the basic syntax:
Instead of writing a condition after the while
keyword, we just write the truth value directly to indicate that the condition will always be True
.
Here we have an example:
>>> while True:
print(0)
0
0
0
0
0
0
0
0
0
0
0
0
0
Traceback (most recent call last):
File "<pyshell#2>", line 2, in <module>
print(0)
KeyboardInterrupt
The loop runs until CTRL + C
is pressed, but Python also has a break
statement that we can use directly in our code to stop this type of loop.
The break
statement
This statement is used to stop a loop immediately. You should think of it as a red «stop sign» that you can use in your code to have more control over the behavior of the loop.
According to the Python Documentation:
The
break
statement, like in C, breaks out of the innermost enclosingfor
orwhile
loop.
This diagram illustrates the basic logic of the break
statement:
break
statement
This is the basic logic of the break
statement:
- The while loop starts only if the condition evaluates to
True
. - If a
break
statement is found at any point during the execution of the loop, the loop stops immediately. - Else, if
break
is not found, the loop continues its normal execution and it stops when the condition evaluates toFalse
.
We can use break
to stop a while loop when a condition is met at a particular point of its execution, so you will typically find it within a conditional statement, like this:
while True:
# Code
if <condition>:
break
# Code
This stops the loop immediately if the condition is True
.
💡 Tip: You can (in theory) write a break
statement anywhere in the body of the loop. It doesn’t necessarily have to be part of a conditional, but we commonly use it to stop the loop when a given condition is True
.
Here we have an example of break
in a while True
loop:
Let’s see it in more detail:
The first line defines a while True
loop that will run indefinitely until a break
statement is found (or until it is interrupted with CTRL + C
).
while True:
The second line asks for user input. This input is converted to an integer and assigned to the variable user_input
.
user_input = int(input("Enter an integer: "))
The third line checks if the input is odd.
if user_input % 2 != 0:
If it is, the message This number is odd
is printed and the break
statement stops the loop immediately.
print("This number of odd")
break
Else, if the input is even , the message This number is even
is printed and the loop starts again.
print("This number is even")
The loop will run indefinitely until an odd integer is entered because that is the only way in which the break
statement will be found.
Here we have an example with custom user input:
Enter an integer: 4
This number is even
Enter an integer: 6
This number is even
Enter an integer: 8
This number is even
Enter an integer: 3
This number is odd
>>>
🔸 In Summary
- While loops are programming structures used to repeat a sequence of statements while a condition is
True
. They stop when the condition evaluates toFalse
. - When you write a while loop, you need to make the necessary updates in your code to make sure that the loop will eventually stop.
- An infinite loop is a loop that runs indefinitely and it only stops with external intervention or when a
break
statement is found. - You can stop an infinite loop with
CTRL + C
. - You can generate an infinite loop intentionally with
while True
. - The
break
statement can be used to stop a while loop immediately.
I really hope you liked my article and found it helpful. Now you know how to work with While Loops in Python.
Follow me on Twitter @EstefaniaCassN and if you want to learn more about this topic, check out my online course Python Loops and Looping Techniques: Beginner to Advanced.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Welcome! If you want to learn how to work with while loops in Python, then this article is for you.
While loops are very powerful programming structures that you can use in your programs to repeat a sequence of statements.
In this article, you will learn:
- What while loops are.
- What they are used for.
- When they should be used.
- How they work behind the scenes.
- How to write a while loop in Python.
- What infinite loops are and how to interrupt them.
- What
while True
is used for and its general syntax. - How to use a
break
statement to stop a while loop.
You will learn how while loops work behind the scenes with examples, tables, and diagrams.
Are you ready? Let’s begin. 🔅
🔹 Purpose and Use Cases for While Loops
Let’s start with the purpose of while loops. What are they used for?
They are used to repeat a sequence of statements an unknown number of times. This type of loop runs while a given condition is True
and it only stops when the condition becomes False
.
When we write a while loop, we don’t explicitly define how many iterations will be completed, we only write the condition that has to be True
to continue the process and False
to stop it.
💡 Tip: if the while loop condition never evaluates to False
, then we will have an infinite loop, which is a loop that never stops (in theory) without external intervention.
These are some examples of real use cases of while loops:
- User Input: When we ask for user input, we need to check if the value entered is valid. We can’t possibly know in advance how many times the user will enter an invalid input before the program can continue. Therefore, a while loop would be perfect for this scenario.
- Search: searching for an element in a data structure is another perfect use case for a while loop because we can’t know in advance how many iterations will be needed to find the target value. For example, the Binary Search algorithm can be implemented using a while loop.
- Games: In a game, a while loop could be used to keep the main logic of the game running until the player loses or the game ends. We can’t know in advance when this will happen, so this is another perfect scenario for a while loop.
🔸 How While Loops Work
Now that you know what while loops are used for, let’s see their main logic and how they work behind the scenes. Here we have a diagram:
Let’s break this down in more detail:
- The process starts when a while loop is found during the execution of the program.
- The condition is evaluated to check if it’s
True
orFalse
. - If the condition is
True
, the statements that belong to the loop are executed. - The while loop condition is checked again.
- If the condition evaluates to
True
again, the sequence of statements runs again and the process is repeated. - When the condition evaluates to
False
, the loop stops and the program continues beyond the loop.
One of the most important characteristics of while loops is that the variables used in the loop condition are not updated automatically. We have to update their values explicitly with our code to make sure that the loop will eventually stop when the condition evaluates to False
.
🔹 General Syntax of While Loops
Great. Now you know how while loops work, so let’s dive into the code and see how you can write a while loop in Python. This is the basic syntax:
These are the main elements (in order):
- The
while
keyword (followed by a space). - A condition to determine if the loop will continue running or not based on its truth value (
True
orFalse
). - A colon (
:
) at the end of the first line. - The sequence of statements that will be repeated. This block of code is called the «body» of the loop and it has to be indented. If a statement is not indented, it will not be considered part of the loop (please see the diagram below).
💡 Tip: The Python style guide (PEP recommends using 4 spaces per indentation level. Tabs should only be used to remain consistent with code that is already indented with tabs.
Now that you know how while loops work and how to write them in Python, let’s see how they work behind the scenes with some examples.
How a Basic While Loop Works
Here we have a basic while loop that prints the value of i
while i
is less than 8 (i < 8
):
i = 4
while i < 8:
print(i)
i += 1
If we run the code, we see this output:
4
5
6
7
Let’s see what happens behind the scenes when the code runs:
- Iteration 1: initially, the value of
i
is 4, so the conditioni < 8
evaluates toTrue
and the loop starts to run. The value ofi
is printed (4) and this value is incremented by 1. The loop starts again. - Iteration 2: now the value of
i
is 5, so the conditioni < 8
evaluates toTrue
. The body of the loop runs, the value ofi
is printed (5) and this valuei
is incremented by 1. The loop starts again. - Iterations 3 and 4: The same process is repeated for the third and fourth iterations, so the integers 6 and 7 are printed.
- Before starting the fifth iteration, the value of
i
is8
. Now the while loop conditioni < 8
evaluates toFalse
and the loop stops immediately.
💡 Tip: If the while loop condition is False
before starting the first iteration, the while loop will not even start running.
User Input Using a While Loop
Now let’s see an example of a while loop in a program that takes user input. We will the input()
function to ask the user to enter an integer and that integer will only be appended to list if it’s even.
This is the code:
# Define the list
nums = []
# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
# Ask for user input and store it in a variable as an integer.
user_input = int(input("Enter an integer: "))
# If the input is an even number, add it to the list
if user_input % 2 == 0:
nums.append(user_input)
The loop condition is len(nums) < 4
, so the loop will run while the length of the list nums
is strictly less than 4.
Let’s analyze this program line by line:
- We start by defining an empty list and assigning it to a variable called
nums
.
nums = []
- Then, we define a while loop that will run while
len(nums) < 4
.
while len(nums) < 4:
- We ask for user input with the
input()
function and store it in theuser_input
variable.
user_input = int(input("Enter an integer: "))
💡 Tip: We need to convert (cast) the value entered by the user to an integer using the int()
function before assigning it to the variable because the input()
function returns a string (source).
- We check if this value is even or odd.
if user_input % 2 == 0:
- If it’s even, we append it to the
nums
list.
nums.append(user_input)
- Else, if it’s odd, the loop starts again and the condition is checked to determine if the loop should continue or not.
If we run this code with custom user input, we get the following output:
Enter an integer: 3
Enter an integer: 4
Enter an integer: 2
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6
Enter an integer: 3
Enter an integer: 4
This table summarizes what happens behind the scenes when the code runs:
💡 Tip: The initial value of len(nums)
is 0
because the list is initially empty. The last column of the table shows the length of the list at the end of the current iteration. This value is used to check the condition before the next iteration starts.
As you can see in the table, the user enters even integers in the second, third, sixth, and eight iterations and these values are appended to the nums
list.
Before a «ninth» iteration starts, the condition is checked again but now it evaluates to False
because the nums
list has four elements (length 4), so the loop stops.
If we check the value of the nums
list when the process has been completed, we see this:
>>> nums
[4, 2, 6, 4]
Exactly what we expected, the while loop stopped when the condition len(nums) < 4
evaluated to False
.
Now you know how while loops work behind the scenes and you’ve seen some practical examples, so let’s dive into a key element of while loops: the condition.
🔹 Tips for the Condition in While Loops
Before you start working with while loops, you should know that the loop condition plays a central role in the functionality and output of a while loop.
You must be very careful with the comparison operator that you choose because this is a very common source of bugs.
For example, common errors include:
- Using
<
(less than) instead of<=
(less than or equal to) (or vice versa). - Using
>
(greater than) instead of>=
(greater than or equal to) (or vice versa).
This can affect the number of iterations of the loop and even its output.
Let’s see an example:
If we write this while loop with the condition i < 9
:
i = 6
while i < 9:
print(i)
i += 1
We see this output when the code runs:
6
7
8
The loop completes three iterations and it stops when i
is equal to 9
.
This table illustrates what happens behind the scenes when the code runs:
- Before the first iteration of the loop, the value of
i
is 6, so the conditioni < 9
isTrue
and the loop starts running. The value ofi
is printed and then it is incremented by 1. - In the second iteration of the loop, the value of
i
is 7, so the conditioni < 9
isTrue
. The body of the loop runs, the value ofi
is printed, and then it is incremented by 1. - In the third iteration of the loop, the value of
i
is 8, so the conditioni < 9
isTrue
. The body of the loop runs, the value ofi
is printed, and then it is incremented by 1. - The condition is checked again before a fourth iteration starts, but now the value of
i
is 9, soi < 9
isFalse
and the loop stops.
In this case, we used <
as the comparison operator in the condition, but what do you think will happen if we use <=
instead?
i = 6
while i <= 9:
print(i)
i += 1
We see this output:
6
7
8
9
The loop completes one more iteration because now we are using the «less than or equal to» operator <=
, so the condition is still True
when i
is equal to 9
.
This table illustrates what happens behind the scenes:
Four iterations are completed. The condition is checked again before starting a «fifth» iteration. At this point, the value of i
is 10
, so the condition i <= 9
is False
and the loop stops.
🔸 Infinite While Loops
Now you know how while loops work, but what do you think will happen if the while loop condition never evaluates to False
?
What are Infinite While Loops?
Remember that while loops don’t update variables automatically (we are in charge of doing that explicitly with our code). So there is no guarantee that the loop will stop unless we write the necessary code to make the condition False
at some point during the execution of the loop.
If we don’t do this and the condition always evaluates to True
, then we will have an infinite loop, which is a while loop that runs indefinitely (in theory).
Infinite loops are typically the result of a bug, but they can also be caused intentionally when we want to repeat a sequence of statements indefinitely until a break
statement is found.
Let’s see these two types of infinite loops in the examples below.
💡 Tip: A bug is an error in the program that causes incorrect or unexpected results.
Example of Infinite Loop
This is an example of an unintentional infinite loop caused by a bug in the program:
# Define a variable
i = 5
# Run this loop while i is less than 15
while i < 15:
# Print a message
print("Hello, World!")
Analyze this code for a moment.
Don’t you notice something missing in the body of the loop?
That’s right!
The value of the variable i
is never updated (it’s always 5
). Therefore, the condition i < 15
is always True
and the loop never stops.
If we run this code, the output will be an «infinite» sequence of Hello, World!
messages because the body of the loop print("Hello, World!")
will run indefinitely.
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
.
.
.
# Continues indefinitely
To stop the program, we will need to interrupt the loop manually by pressing CTRL + C
.
When we do, we will see a KeyboardInterrupt
error similar to this one:
To fix this loop, we will need to update the value of i
in the body of the loop to make sure that the condition i < 15
will eventually evaluate to False
.
This is one possible solution, incrementing the value of i
by 2 on every iteration:
i = 5
while i < 15:
print("Hello, World!")
# Update the value of i
i += 2
Great. Now you know how to fix infinite loops caused by a bug. You just need to write code to guarantee that the condition will eventually evaluate to False
.
Let’s start diving into intentional infinite loops and how they work.
🔹 How to Make an Infinite Loop with While True
We can generate an infinite loop intentionally using while True
. In this case, the loop will run indefinitely until the process is stopped by external intervention (CTRL + C
) or when a break
statement is found (you will learn more about break
in just a moment).
This is the basic syntax:
Instead of writing a condition after the while
keyword, we just write the truth value directly to indicate that the condition will always be True
.
Here we have an example:
>>> while True:
print(0)
0
0
0
0
0
0
0
0
0
0
0
0
0
Traceback (most recent call last):
File "<pyshell#2>", line 2, in <module>
print(0)
KeyboardInterrupt
The loop runs until CTRL + C
is pressed, but Python also has a break
statement that we can use directly in our code to stop this type of loop.
The break
statement
This statement is used to stop a loop immediately. You should think of it as a red «stop sign» that you can use in your code to have more control over the behavior of the loop.
According to the Python Documentation:
The
break
statement, like in C, breaks out of the innermost enclosingfor
orwhile
loop.
This diagram illustrates the basic logic of the break
statement:
break
statement
This is the basic logic of the break
statement:
- The while loop starts only if the condition evaluates to
True
. - If a
break
statement is found at any point during the execution of the loop, the loop stops immediately. - Else, if
break
is not found, the loop continues its normal execution and it stops when the condition evaluates toFalse
.
We can use break
to stop a while loop when a condition is met at a particular point of its execution, so you will typically find it within a conditional statement, like this:
while True:
# Code
if <condition>:
break
# Code
This stops the loop immediately if the condition is True
.
💡 Tip: You can (in theory) write a break
statement anywhere in the body of the loop. It doesn’t necessarily have to be part of a conditional, but we commonly use it to stop the loop when a given condition is True
.
Here we have an example of break
in a while True
loop:
Let’s see it in more detail:
The first line defines a while True
loop that will run indefinitely until a break
statement is found (or until it is interrupted with CTRL + C
).
while True:
The second line asks for user input. This input is converted to an integer and assigned to the variable user_input
.
user_input = int(input("Enter an integer: "))
The third line checks if the input is odd.
if user_input % 2 != 0:
If it is, the message This number is odd
is printed and the break
statement stops the loop immediately.
print("This number of odd")
break
Else, if the input is even , the message This number is even
is printed and the loop starts again.
print("This number is even")
The loop will run indefinitely until an odd integer is entered because that is the only way in which the break
statement will be found.
Here we have an example with custom user input:
Enter an integer: 4
This number is even
Enter an integer: 6
This number is even
Enter an integer: 8
This number is even
Enter an integer: 3
This number is odd
>>>
🔸 In Summary
- While loops are programming structures used to repeat a sequence of statements while a condition is
True
. They stop when the condition evaluates toFalse
. - When you write a while loop, you need to make the necessary updates in your code to make sure that the loop will eventually stop.
- An infinite loop is a loop that runs indefinitely and it only stops with external intervention or when a
break
statement is found. - You can stop an infinite loop with
CTRL + C
. - You can generate an infinite loop intentionally with
while True
. - The
break
statement can be used to stop a while loop immediately.
I really hope you liked my article and found it helpful. Now you know how to work with While Loops in Python.
Follow me on Twitter @EstefaniaCassN and if you want to learn more about this topic, check out my online course Python Loops and Looping Techniques: Beginner to Advanced.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Цикл while позволяет повторить одно или несколько действий до тех пор, пока заданное условие остается истинным.
Содержание страницы: |
---|
1. Цикл while в Python |
1.2. Как прервать цикл while |
1.3. Флаги в цикле while |
2.1. Команда break в цикле while |
2.2. Команда continue в цикле while |
3. Предотвращение зацикливания в цикле while |
4. Цикл while со списками |
5. Цикл while со словарями |
1. Цикл while в Python
Цикл while в Python используется во многих программах. Он позволяет выполнять программу пока остается истинным условие. Приведем пример перебора числовой последовательности в заданном диапазоне.
>>> number = 1 # присваиваем начальное значение переменной
>>> while number <= 7: # запускаем цикл при условии значение number <=7
… print(number) # выводим значение number при каждом цикле
… number += 1 # после каждого цикла увеличиваем значение на 1
…
1
2
3
4
5
6
7
Вначале присваиваем значение переменной number. Затем запускаем цикл while до тех пор, пока значение переменной number не будет больше 7. При каждом проходе цикла выводим значение number и затем увеличиваем его на 1. Как только значение number станет больше 7 цикл прекращается.
1.2. Как прервать цикл while на Python.
Предположим, что вам нужно остановить программу, когда пользователь захочет этого. Для этого в программе определяем признак завершения, и программа работает до тех пор, пока пользователь не ввел нужное значение. Признаком завершения может быть как число, так и строка или символ. Приведем пример простого цикла while при котором пользователь вводит слово, а оно возвращается, наоборот.
prompt = «nВведите любое слово, и оно будет выведено наоборот»
prompt += «nЕсли надоело введите команду ‘стоп’.n»
message = »
while message != «стоп»:
message = input(prompt)
if message != «стоп»:
print(message[::-1])
else:
print(«Программа завершена»)
В начале создаем сообщение prompt (посказку) которое объясняет пользователю что за программа и как ее можно завершить. Затем создается переменная message и ей присваивается пустое значение. Важно переменную message определить до запуска цикла, присвоить ей можно любое значение или пустую строку. При запуске цикла while идет проверка совпадает ли значение message с условием продолжения цикла. При каждом выполнение цикла на экран выводятся правила цикла и условия его завершения. Дальше можно запустить команду if-else для проверки условия, если пользователь не ввел строку «стоп«, то выводим строку пользователя на экран в обратном порядке с помощью сегментации строки [: : -1].
Введите любое слово, и оно будет выведено наоборот
Если надоело введите команду ‘стоп’.
python лучший язык программирования
яинавориммаргорп кызя йишчул nohtyp
Введите любое слово, и оно будет выведено наоборот
Если надоело введите команду ‘стоп’.
123456789
987654321
Введите любое слово, и оно будет выведено наоборот
Если надоело введите команду ‘стоп’.
стоп
Программа завершена
Пока пользователь не введет слово «стоп», цикл будет начинаться заново.
1.3. Флаги в цикле while на Python
Если программа должна выполняться при нескольких условиях, то лучше определить одну переменную — флаг. Переменная — флаг сообщает, должна ли программа выполняться при каждом цикле. Для флага достаточно определить два состояния True — в котором программа продолжит выполнение и False — завершение программы. В результате в начале цикла while достаточно проверить всего одно условие для запуска программы, а все остальные проверки организовать в остальном коде.
prompt = «nВведите любое слово, и оно будет выведено наоборот»
prompt += «nЕсли надоело введите команду ‘стоп’n»
active = True
while active:
message = input(prompt)
if message == «стоп»:
active = False
print(«Программа завершена»)
else:
print(message[::-1])
В примере переменной active присваивается True и программа будет выполняться до тех пор, пока переменная active не станет равной False. Результат работы этой программы ничем не будет отличаться от программы в разделе 1.2. Вот что получим мы на выходе.
Введите любое слово, и оно будет выведено наоборот
Если надоело введите команду ‘стоп’
Python
nohtyP
Введите любое слово, и оно будет выведено наоборот
Если надоело введите команду ‘стоп’
стоп
Программа завершена
Программа завершится если пользователь введет «стоп». После этого переменная active становится равной False и действие цикла прекращается.
2.1. Команда break в цикле while на Python
С помощью команды break так же можно прервать цикл while. Цикл, который начинается с while True выполняется бесконечно, пока не будет выполнена команда break.
prompt = «nВведите столицу США с заглавной буквы: «
active = True
while active:
capital = input(prompt)
if capital == ‘Вашингтон’:
print(‘Совершенно верно’)
break
else:
print(f»{capital} не является столицей США»)
В результате цикл while будет выполняться до тех пор, пока не будет введен правильный ответ, после чего сработает команда break и произойдет выход из цикла.
Введите столицу США с заглавной буквы: Лондон
Лондон не является столицей США
Введите столицу США с заглавной буквы: Москва
Москва не является столицей США
Введите столицу США с заглавной буквы: Вашингтон
Совершенно верно
2.2. Команда continue в цикле while на Python
Предположим, что вам нужно прервать цикл while при выполнение каких-либо условий и запустить его заново. Для этого можно воспользоваться командой continue. Напишем цикл while, который выводит только четные числа в диапазоне от 1 до 20:
>>> number = 0
>>> while number < 20:
… number += 1
… if number % 2 == 1:
… continue
… print(number, end=’ ‘)
…
2 4 6 8 10 12 14 16 18 20 >>>
Сначала создадим переменную number и присвоим ей начальное значение. После идет проверка условий цикла что значение number меньше 20. При входе в цикл значение number увеличивается на 1 и затем команда if проверяет остаток от деления на 2. Если остаток равен одному, то число не четное, команда continue приказывает Python игнорировать остаток кода и цикл запускается заново. Если остаток от деления равен нулю, то число выводится на экран и так до того пока number будет равен 20, затем условия цикла while не будут выполнены и цикл прекратится.
3. Предотвращение зацикливания в циклах while на Python
В каждом цикле должно быть предусмотрена возможность завершения, чтобы цикл while не выполнялся бесконечно. Например, если в предыдущем примере мы пропустили бы строку number += 1 , то значение number всегда будет равно 0 и цикл будет продолжаться до бесконечности
>>> number = 0
>>> while number < 20:
… if number % 2 == 1:
… continue
… print(number, end=’ ‘)
…
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 …….
Для предотвращения зацикливания в терминальном окне введите Ctrl + C и всегда заранее проверяйте все условия цикла while и пути выхода из него.
4. Цикл while со списками в Python
Для изменения списков в процессе обработки удобно использовать цикл while. К примеру, у нас есть целый список пользователей, который может состоять из тысяч пользователей и нам нужно будут удалить всех пользователей с определенным именем. Нам уже известно, что метод remove() для списков удаляет лишь первое вхождение заданного значения в список, но нам нужно удалить их все. В этом случае мы можем запустить цикл while:
>>> login = [‘qwerty’, ‘arfa’, ‘bond’, ‘chelsy’, ‘qwerty’, ‘serg’, ‘cat’, ‘qwerty’]
>>> while ‘qwerty’ in login:
… login.remove(‘qwerty’)
…
>>> print(login)
[‘arfa’, ‘bond’, ‘chelsy’, ‘serg’, ‘cat’]
В результате при запуске цикла while проверяется условия нахождения ‘qwerty‘ в списке login. Затем после первого удаления из списка, цикл запускается снова и Python проверяет наличие ‘qwerty‘ в списке заново и так до тех, пор пока будет выполняться условие цикла while.
5. Цикл while со словарями в Python
При каждом проходе цикла while программа может выполнять любое действие. Так же, как и со списками, цикл while работает и со словарями. Создадим программу, которая будет запрашивать у посетителя имя и записывать ответы на заданный вопрос и в конце выводить словарь на экран:
interview = {}
active = True
while active:
# Запрашиваем имя и ответ на вопрос
name = input(«nКак вас зовут? «)
question = input(«Какая марка автомобиля вам нравиться «)
# Создаем список с ответами и добавляем первый ответ
answers = []
answers.append(question)
# Ответ сохраняем в словаре «имя: список ответов»
interview[name] = answers
# Запускаем второй цикл с возможностью добавления еще ответов к одному пользователю
active_2 = True
while active_2:
repeat = input(«Желаете добавить еще один автомобиль? (yes/no) «)
if repeat == ‘no’:
active_2 = False
else:
question_n = input(«Какая марка автомобиля вам еще нравиться «)
# Добавляем ответ в список
answers.append(question_n)
# Вопрос о продолжение опроса
repeat = input(«Желаете продолжить опрос? (yes/no) «)
if repeat == ‘no’:
active = False
print(«nОпрос завершен, все результаты:»)
# Переберем словарь и посмотрим ответы
for name, questions in interview.items():
print(f»n{name.title()} любит автомобили марки:»)
for question in questions:
print(f»t{question.title()}»)
В начале программы создаем словарь interview в который в будущем будем добавлять посетителя с его ответами. Затем устанавливаем флаг продолжения опроса active = True. Пока active = True Python будет выполнять цикл while. При запуске цикла посетителю предлагается представиться и ввести ответ на заданный вопрос. Затем сразу создадим список ответов answers на всякий случай, если посетитель захочет дать несколько ответов и добавляем его в словарь. После запускаем второй цикл while с вопросом добавить еще один ответ. Количество ответов бесконечно, и посетитель сам решает, когда прервать программу. Если ответов больше нет, то возвращаемся к первому циклу и предлагаем ввести нового посетителя с опросом. После окончания цикла while выведем на экран всех посетителей и их ответы. Если запустить программу и ввести несколько пользователей с ответами, то результат будет выглядеть так:
Как вас зовут? bob
Какая марка автомобиля вам нравиться: audi
Желаете добавить еще один автомобиль? (yes/no) yes
Какая марка автомобиля вам еще нравиться: bmw
Желаете добавить еще один автомобиль? (yes/no) yes
Какая марка автомобиля вам еще нравиться: ford
Желаете добавить еще один автомобиль? (yes/no) no
Желаете продолжить опрос? (yes/no) yes
Как вас зовут? Artem
Какая марка автомобиля вам нравиться: porshe
Желаете добавить еще один автомобиль? (yes/no) no
Желаете продолжить опрос? (yes/no) no
Опрос завершен, все результаты:
Bob любит автомобили марки:
Audi
Bmw
Ford
Artem любит автомобили марки:
Porshe
Далее: Функции в Python
Назад: Множества в Python
Выполнение программ, написанных на любом языке программирования, по умолчанию является последовательным. Иногда нам может понадобиться изменить выполнение программы. Выполнение определенного кода может потребоваться повторить несколько раз.
Для этого в языках программирования предусмотрены различные типы циклов, которые способны повторять определенный код несколько раз. Чтобы понять принцип работы оператора цикла, рассмотрим следующую схему.
Циклы упрощают сложные задачи до простых. Он позволяет нам изменить поток программы таким образом, что вместо того, чтобы писать один и тот же код снова и снова, мы можем повторять его конечное число раз. Например, если нам нужно вывести первые 10 натуральных чисел, то вместо того, чтобы использовать оператор print 10 раз, мы можем вывести их внутри цикла, который выполняется до 10 итераций.
Преимущества циклов
В Python преимущества циклов, как и в других язвках программирования, заключаются в следующем:
- Это обеспечивает возможность повторного использования кода.
- Используя циклы, нам не нужно писать один и тот же код снова и снова.
- С помощью циклов мы можем перебирать элементы структур данных (массивов или связанных списков).
В Python существуют следующие операторы циклов.
Оператор цикла | Описание |
---|---|
for |
Цикл for используется в том случае, когда необходимо выполнить некоторую часть кода до тех пор, пока не будет выполнено заданное условие. Цикл for также называют циклом c предусловием. Лучше использовать цикл for, если количество итераций известно заранее. |
while |
Цикл while используется в сценарии, когда мы не знаем заранее количество итераций. Блок операторов в цикле while выполняется до тех пор, пока не будет выполнено условие, указанное в цикле while. Его также называют циклом с предварительной проверкой условия. |
do-while |
Цикл do-while продолжается до тех пор, пока не будет выполнено заданное условие. Его также называют циклом с пстусловием. Он используется, когда необходимо выполнить цикл хотя бы один раз. |
Цикл for в Python
Цикл for
в Python используется для многократного повторения операторов или части программы. Он часто используется для обхода структур данных, таких как список, кортеж или словарь.
Синтаксис цикла for
в python приведен ниже.
for iterating_var in sequence:
statement(s)
Цикл For с использованием последовательности
Пример 1: Итерация строки с помощью цикла for
str = "Python"
for i in str:
print(i)
Вывод:
P
y
t
h
o
n
Пример 2: Программа для печати таблицы заданного числа.
list = [1,2,3,4,5,6,7,8,9,10]
n = 5
for i in list:
c = n*i
print(c)
Вывод:
5
10
15
20
25
30
35
40
45
50s
Пример 3: Программа для печати суммы заданного списка.
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
Вывод:
The sum is: 183
Цикл For с использованием функции range()
Функция range()
Функция range()
используется для генерации последовательности чисел. Если мы передадим range(10)
, она сгенерирует числа от 0
до 9
. Синтаксис функции range()
приведен ниже.
range(start,stop,step size)
Start
означает начало итерации.Stop
означает, что цикл будет повторяться до stop-1.range(1,5)
будет генерировать числа от 1 до 4 итераций. Это необязательный параметр.- Размер шага используется для пропуска определенных чисел в итерации. Его использование необязательно. По умолчанию размер шага равен 1. Это необязательно.
Рассмотрим следующие примеры:
Пример 1: Программа для печати чисел по порядку.
for i in range(10):
print(i,end = ' ')
Вывод:
0 1 2 3 4 5 6 7 8 9
Пример 2: Программа для печати таблицы заданного числа.
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
Вывод:
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
Пример 3: Программа для печати четного числа с использованием размера шага в range().
n = int(input("Enter the number "))
for i in range(2,n,2):
print(i)
Вывод:
Enter the number 20
2
4
6
8
10
12
14
16
18
Мы также можем использовать функцию range()
с последовательностью чисел. Функция len()
сочетается с функцией range()
, которая выполняет итерацию по последовательности с использованием индексации. Рассмотрим следующий пример.
list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])
Вывод:
Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh
Вложенный цикл for в python
Python позволяет нам вложить любое количество циклов for внутрь цикла for. Внутренний цикл выполняется n раз за каждую итерацию внешнего цикла. Синтаксис приведен ниже.
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
Пример 1: Вложенный цикл for
# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Вывод:
Enter the rows:5
*
**
***
****
*****
Пример 2: Программа для печати пирамиды чисел.
rows = int(input("Enter the rows"))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()
Вывод:
1
22
333
4444
55555
Использование оператора else в цикле for
В отличие от других языков, таких как C, C++ или Java, Python позволяет нам использовать оператор else с циклом for
, который может быть выполнен только тогда, когда все итерации исчерпаны. Здесь мы должны заметить, что если цикл содержит какой-либо оператор break, то оператор else
не будет выполнен.
Пример 1
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")
Вывод:
0
1
2
3
4
for loop completely exhausted, since there is no break.
Цикл for
полностью исчерпал себя, так как нет прерывания.
Пример 2
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
В приведенном выше примере цикл прерван из-за оператора break, поэтому оператор else
не будет выполнен. Будет выполнен оператор, находящийся непосредственно рядом с блоком else
.
Вывод:
0
Цикл был прерван, благодаря оператору break.
Цикл while в Python
Цикл while позволяет выполнять часть кода до тех пор, пока заданное условие не станет ложным. Он также известен как цикл с предварительной проверкой условия.
Его можно рассматривать как повторяющийся оператор if
. Когда мы не знаем количество итераций, цикл while является наиболее эффективным.
Синтаксис приведен ниже.
while expression:
statements
Здесь утверждения могут быть одним утверждением или группой утверждений. Выражение должно быть любым допустимым выражением Python, приводящим к true
или false
. Истиной является любое ненулевое значение, а ложью — 0
.
Операторы управления циклом
Мы можем изменить обычную последовательность выполнения цикла while с помощью оператора управления циклом. Когда выполнение цикла while завершается, все автоматические объекты, определенные в этой области видимости, уничтожаются. Python предлагает следующие управляющие операторы для использования в цикле while.
1. Оператор continue — Когда встречается оператор continue
, управление переходит в начало цикла. Давайте разберем следующий пример.
# prints all letters except 'a' and 't'
i = 0
str1 = 'javatpoint'
while i < len(str1):
if str1[i] == 'a' or str1[i] == 't':
i += 1
continue
print('Current Letter :', a[i])
i += 1
Вывод:
Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n
2. Оператор break — Когда встречается оператор break
, он выводит управление из цикла.
Пример:
# The control transfer is transfered
# when break statement soon it sees t
i = 0
str1 = 'javatpoint'
while i < len(str1):
if str1[i] == 't':
i += 1
break
print('Current Letter :', str1[i])
i += 1
Вывод:
Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a
3. Оператор pass — Оператор pass
используется для объявления пустого цикла. Он также используется для определения пустого класса, функции и оператора управления. Давайте разберем следующий пример.
# An empty loop
str1 = 'javatpoint'
i = 0
while i < len(str1):
i += 1
pass
print('Value of i :', i)
Вывод
Value of i : 10
Пример 1: Программа для печати от 1 до 10 с использованием цикла while
i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1
Вывод
1
2
3
4
5
6
7
8
9
10
Пример 2: Программа для печати таблицы заданных чисел.
i=1
number=0
b=9
number = int(input("Enter the number:"))
while i<=10:
print("%d X %d = %d n"%(number,i,number*i))
i = i+1
Вывод
Enter the number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Бесконечный цикл while
Если условие, заданное в цикле while, никогда не станет ложным, то цикл while никогда не завершится, и он превратится в бесконечный цикл while.
Любое ненулевое значение в цикле while
указывает на всегда истинное состояние, в то время как ноль указывает на всегда ложное состояние. Такой подход полезен, если мы хотим, чтобы наша программа непрерывно выполнялась в цикле без каких-либо помех.
Пример 1
while (1):
print("Hi! we are inside the infinite while loop"
Вывод
Hi! we are inside the infinite while loop
Hi! we are inside the infinite while loop
Пример 2
var = 1
while(var != 2):
i = int(input("Enter the number:"))
print("Entered value is %d"%(i))
Вывод
Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time
Использование else в цикле while
Python позволяет нам также использовать оператор else
с циклом while
. Блок else
выполняется, когда условие, заданное в операторе while
, становится ложным. Как и в случае с циклом for
, если цикл while
прервать с помощью оператора break
, то блок else
не будет выполнен, а будет выполнен оператор, присутствующий после блока else
. Оператор else
необязателен для использования с циклом while
. Рассмотрим следующий пример.
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")
i=1
while(i<=5):
print(i)
i=i+1
if(i==3):
break
else:
print("The while loop exhausted")
Вывод
1
2
В приведенном выше коде, когда встречается оператор break
, цикл while
останавливает свое выполнение и пропускает оператор else
.
Программа для печати чисел Фибоначчи до заданного предела
terms = int(input("Enter the terms "))
# first two intial terms
a = 0
b = 1
count = 0
# check if the number of terms is Zero or negative
if (terms <= 0):
print("Please enter a valid integer")
elif (terms == 1):
print("Fibonacci sequence upto",limit,":")
print(a)
else:
print("Fibonacci sequence:")
while (count < terms) :
print(a, end = ' ')
c = a + b
# updateing values
a = b
b = c
count += 1
Enter the terms 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
Оператор прерывания в Python
Break — это ключевое слово в python, которое используется для вывода управления программой из цикла. Оператор break разрывает циклы по одному, то есть в случае вложенных циклов он сначала разрывает внутренний цикл, а затем переходит к внешним циклам. Другими словами, можно сказать, что break используется для прерывания текущего выполнения программы, и управление переходит на следующую строку после цикла.
Прерывание обычно используется в тех случаях, когда нам нужно прервать цикл при заданном условии.
Синтаксис прерывания приведен ниже.
#оператор цикла
break;
Пример:
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");
Вывод:
item matched
found at 2 location
Пример:
str = "python"
for i in str:
if i == 'o':
break
print(i);
Вывод:
p
y
t
h
Пример: оператор break с циклом while
i = 0;
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
print("came out of while loop");
Вывод:
0 1 2 3 4 5 6 7 8 9 came out of while loop
Пример
n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %dn"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
if choice == 0:
break;
n=n+1
Вывод:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table, press 0 for no?1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table, press 0 for no?0
Оператор continue в Python
Оператор continue в Python используется для возврата управления программой в начало цикла. Оператор continue пропускает оставшиеся строки кода внутри цикла и начинает следующую итерацию. В основном он используется для определенного условия внутри цикла, чтобы мы могли пропустить определенный код для конкретного условия.
#loop statements
continue
#the code to be skipped
Рассмотрим следующие примеры.
Пример
i = 0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
Вывод:
1
2
3
4
6
7
8
9
10
Обратите внимание на вывод приведенного выше кода, значение 5 пропущено, потому что мы предоставили условие if
с помощью оператора continue
в цикле while
. Когда оно совпадает с заданным условием, управление передается в начало цикла while
, и он пропускает значение 5 из кода.
Давайте посмотрим на другой пример:
Пример
str = "JavaTpoint"
for i in str:
if(i == 'T'):
continue
print(i)
Вывод:
J
a
v
a
p
o
i
n
t
Оператор pass в python
Оператор pass является нулевым оператором (null operation), поскольку при его выполнении ничего не происходит. Он используется в тех случаях, когда оператор синтаксически необходим, но мы не хотим использовать вместо него какой-либо исполняемый оператор.
Например, он может быть использован при переопределении метода родительского класса в подклассе, но мы не хотим давать его конкретную реализацию в подклассе.
Pass также используется в тех случаях, когда код будет записан где-то, но еще не записан в программном файле. Рассмотрим следующий пример.
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ");
if i==3:
pass
print("nWe are inside pass blockn");
flag = 1
if flag==1:
print("nCame out of passn");
flag=0
Вывод:
Current element: 1 Current element: 2 Current element: 3
We are inside pass block
Came out of pass
Current element: 4 Current element: 5
Python цикл Do While
В Python нет цикла do while. Но мы можем создать подобную программу.
Цикл do while используется для проверки условия после выполнения оператора. Он похож на цикл while, но выполняется хотя бы один раз.
Общий синтаксис цикла Do While (не отностится к python)
do {
//statement
} while (condition);
Пример: цикл do while в Python
i = 1
while True:
print(i)
i = i + 1
if(i > 5):
break
Вывод:
1
2
3
4
5