-
Главная
-
Инструкции
-
Python
-
Операторы break, continue и pass в циклах Python 3
При работе с циклами while
и for
бывает необходимо выполнить принудительный выход, пропустить часть или игнорировать заданные условия. Для первых двух случаев используются операторы break
и continue
Python, а для игнорирования условий — инструкция pass
. Давайте посмотрим на примерах, как работают эти операторы.
Инструкция break
в языке программирования Python прерывает выполнение блока кода. Простейший пример:
for j in 'bananafishbones':
if j == 'f':
break
print(j)
Получаем такой вывод:
b
a
n
a
n
a
Как только программа после нескольких итераций доходит до элемента последовательности, обозначенного буквой f
, цикл (loop) прерывается, поскольку действует оператор break
. Теперь рассмотрим работу этой инструкции в цикле while
:
x = 0
while x < 5:
print(x)
x += 0.5
print('Выход')
Вывод будет следующий (приводим с сокращениями):
0
0.5
…
4.0
4.5
Выход
Как только перестает выполняться условие и x становится равным 5, программа завершает цикл. А теперь перепишем код с использованием инструкции break
:
x = 0
while True:
print(x)
if x >= 4.5:
break
x += 0.5
print('Выход')
Результат тот же:
0
0.5
…
4.0
4.5
Выход
Мы точно так же присвоили x значение 0 и задали условие: пока значение x истинно (True), продолжать выводить его. Код, правда, получился немного длиннее, но бывают ситуации, когда использование оператора прерывания оправданно: например, при сложных условиях или для того, чтобы подстраховаться от создания бесконечного цикла. Уберите из кода выше две строчки:
x = 0
while True:
print(x)
x += 0.5
print('Выход')
И перед нами бесконечный вывод:
0
0.5
…
100
100.5
…
1000000
1000000.5
…
И слово в конце (‘Выход’), таким образом, никогда не будет выведено, поскольку цикл не закончится. Поэтому при работе с последовательностями чисел использование оператора break
убережет вас от сбоев в работе программ, вызываемых попаданием в бесконечный цикл.
Конструкция с else
Иногда необходимо проверить, был ли цикл исполнен до конца или выход произошел с использованием инструкции break
. Для этого добавляется проверка по условию с else
. Напишем программу, которая проверяет фразу на наличие запрещенных элементов:
word = input('Введите слово: ')
for i in word:
if i == 'я':
print('Цикл был прерван, обнаружена буква я')
break
else:
print('Успешное завершение, запрещенных букв не обнаружено')
print('Проверка завершена')
Теперь, если пользователь введет, например, «Привет!», программа выдаст следующее:
Успешное завершение, запрещенных букв не обнаружено
Проверка завершена
Но если во введенном слове будет буква «я», то вывод примет такой вид:
Цикл был прерван, обнаружена буква я
Проверка завершена
Небольшое пояснение: функция input
принимает значение из пользовательского ввода (выражение 'Введите слово: '
необходимо только для пользователя, для корректной программы хватило бы и такой строки: word = input ()
) и присваивает его переменной word
. Последняя при помощи for
поэлементно (в данном случае — побуквенно) анализируется с учетом условия, вводимого if
.
Оператор continue в Python
Если break
дает команду на прерывание, то continue
действует более гибко. Его функция заключается в пропуске определенных элементов последовательности, но без завершения цикла. Давайте напишем программу, которая «не любит» букву «я»:
word = input('Введите слово: ')
for i in word:
if i == 'я':
continue
print(i)
Попробуйте ввести, например, «яблоко», в этом случае вывод будет таким:
б
л
о
к
о
Это происходит потому, что мы задали условие, по которому элемент с определенным значением (в данном случае буква «я») не выводится на экран, но благодаря тому, что мы используем инструкцию continue
, цикл доходит до последней итерации и все «разрешенные» элементы выводятся на экран. Но в коде выше есть одна проблема: если пользователь введет, например, «Яблоко», программа выведет слово полностью, поскольку не учтен регистр:
Я
б
л
о
к
о
Наиболее очевидное решение в данном случае состоит в добавлении и заглавной буквы в блок if
таким образом:
word = input('Введите слово: ')
for i in word:
if i == 'я' or i == 'Я':
continue
print(i)
Оператор pass в Python
Назначение pass
— продолжение цикла независимо от наличия внешних условий. В готовом коде pass
встречается нечасто, но полезен в процессе разработки и применяется в качестве «заглушки» там, где код еще не написан. Например, нам нужно не забыть добавить условие с буквой «я» из примера выше, но сам этот блок по какой-то причине мы пока не написали. Здесь для корректной работы программы и поможет заглушка pass
:
word = input('Введите слово: ')
for i in word:
if i == 'я':
pass
else:
print('Цикл завершен, запрещенных букв не обнаружено')
print('Проверка завершена')
Теперь программа запустится, а pass
будет для нас маркером и сообщит о том, что здесь нужно не забыть добавить условие.
Вот и всё, надеемся, скоро break
, continue
и pass
станут вашими верными друзьями в разработке интересных приложений. Успехов!
Python Continue Statement skips the execution of the program block after the continue statement and forces the control to start the next iteration.
Python Continue Statement
Python Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current iteration only, i.e. when the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped for the current iteration and the next iteration of the loop will begin.
Python continue Statement Syntax
while True: ... if x == 10: continue print(x)
Flowchart of Continue Statement
flowchart of Python continue statement
Continue statement in Python Examples
Demonstration of Continue statement in Python
In this example, we will use continue inside some condition within a loop.
Python3
for
var
in
"Geeksforgeeks"
:
if
var
=
=
"e"
:
continue
print
(var)
Output:
G k s f o r g k s
Explanation: Here we are skipping the print of character ‘e’ using if-condition checking and continue statement.
Printing range with Python Continue Statement
Consider the situation when you need to write a program that prints the number from 1 to 10, but not 6.
It is specified that you have to do this using a loop and only one loop is allowed to use. Here comes the usage of the continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of the loop variable with 6. If it is equal to 6 we will use the continue statement to continue to the next iteration without printing anything, otherwise, we will print the value.
Python3
for
i
in
range
(
1
,
11
):
if
i
=
=
6
:
continue
else
:
print
(i, end
=
" "
)
Output:
1 2 3 4 5 7 8 9 10
Note: The continue statement can be used with any other loop also like the while loop, similarly as it is used with for loop above.
Continue with Nested loops
In this example, we are creating a 2d list that includes the numbers from 1 to 9 and we are traversing in the list with the help of two for loops and we are skipping the print statement when the value is 3.
Python3
nested_list
=
[[
1
,
2
,
3
], [
4
,
5
,
6
], [
7
,
8
,
9
]]
for
i
in
nested_list:
for
j
in
i:
if
j
=
=
3
:
continue
print
(j)
Output
1 2 4 5 6 7 8 9
Continue with While Loop
In this example, we are using a while loop which traverses till 9 if i = 5 then skip the printing of numbers.
Python3
i
=
0
while
i <
10
:
if
i
=
=
5
:
i
+
=
1
continue
print
(i)
i
+
=
1
Output
0 1 2 3 4 6 7 8 9
Usage of Continue Statement
Loops in Python automate and repeat tasks efficiently. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Continue is a type of loop control statement that can alter the flow of the loop.
To read more on pass and break, refer to these articles:
- Python pass statement
- Python break statement
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out — check it out now!
Last Updated :
09 May, 2023
Like Article
Save Article
Back to top
Toggle table of contents sidebar
В Python есть несколько операторов, которые позволяют менять поведение
циклов по умолчанию.
Оператор break#
Оператор break
позволяет досрочно прервать цикл:
-
break прерывает текущий цикл и продолжает выполнение следующих выражений
-
если используется несколько вложенных циклов, break прерывает внутренний цикл
и продолжает выполнять выражения, следующие за блоком
* break может использоваться в циклах for и while
Пример с циклом for:
In [1]: for num in range(10): ...: if num < 7: ...: print(num) ...: else: ...: break ...: 0 1 2 3 4 5 6
Пример с циклом while:
In [2]: i = 0 In [3]: while i < 10: ...: if i == 5: ...: break ...: else: ...: print(i) ...: i += 1 ...: 0 1 2 3 4
Использование break в примере с запросом пароля (файл
check_password_with_while_break.py):
username = input('Введите имя пользователя: ') password = input('Введите пароль: ') while True: if len(password) < 8: print('Пароль слишком короткий\n') elif username in password: print('Пароль содержит имя пользователя\n') else: print('Пароль для пользователя {} установлен'.format(username)) # завершает цикл while break password = input('Введите пароль еще раз: ')
Теперь можно не повторять строку
password = input('Введите пароль еще раз: ')
в каждом ответвлении,
достаточно перенести ее в конец цикла.
И, как только будет введен правильный пароль, break выведет программу из
цикла while.
Оператор continue#
Оператор continue возвращает управление в начало цикла. То есть,
continue позволяет «перепрыгнуть» оставшиеся выражения в цикле и перейти
к следующей итерации.
Пример с циклом for:
In [4]: for num in range(5): ...: if num == 3: ...: continue ...: else: ...: print(num) ...: 0 1 2 4
Пример с циклом while:
In [5]: i = 0 In [6]: while i < 6: ....: i += 1 ....: if i == 3: ....: print("Пропускаем 3") ....: continue ....: print("Это никто не увидит") ....: else: ....: print("Текущее значение: ", i) ....: Текущее значение: 1 Текущее значение: 2 Пропускаем 3 Текущее значение: 4 Текущее значение: 5 Текущее значение: 6
Использование continue в примере с запросом пароля (файл
check_password_with_while_continue.py):
username = input('Введите имя пользователя: ') password = input('Введите пароль: ') password_correct = False while not password_correct: if len(password) < 8: print('Пароль слишком короткий\n') elif username in password: print('Пароль содержит имя пользователя\n') else: print('Пароль для пользователя {} установлен'.format(username)) password_correct = True continue password = input('Введите пароль еще раз: ')
Тут выход из цикла выполнятся с помощью проверки флага
password_correct. Когда был введен правильный пароль, флаг выставляется
равным True, и с помощью continue выполняется переход в начало цикла,
перескочив последнюю строку с запросом пароля.
Результат выполнения будет таким:
$ python check_password_with_while_continue.py Введите имя пользователя: nata Введите пароль: nata12 Пароль слишком короткий Введите пароль еще раз: natalksdjflsdjf Пароль содержит имя пользователя Введите пароль еще раз: asdfsujljhdflaskjdfh Пароль для пользователя nata установлен
Оператор pass#
Оператор pass
ничего не делает. Фактически, это такая заглушка для
объектов.
Например, pass
может помочь в ситуации, когда нужно прописать
структуру скрипта. Его можно ставить в циклах, функциях, классах. И это
не будет влиять на исполнение кода.
Пример использования pass:
In [6]: for num in range(5): ....: if num < 3: ....: pass ....: else: ....: print(num) ....: 3 4
Курсы
Циклы for и while, операторы break и continue, волшебное слово else
Я расскажу о циклах for и while, операторах break и continue, а также о слове else, которое, будучи употребленное с циклом, может сделать программный код несколько более понятным.
Цикл while
While — один из самых универсальных циклов в Python, поэтому довольно медленный. Выполняет тело цикла до тех пор, пока условие цикла истинно.
|
|
Цикл for
Общее понятие
Цикл for уже чуточку сложнее, чуть менее универсальный, но выполняется гораздо быстрее цикла while. Этот цикл проходится по любому итерируемому объекту (например строке или списку), и во время каждого прохода выполняет тело цикла.
Цикл for используется в том случае, когда необходимо выполнить некоторую часть кода до тех пор, пока не будет выполнено заданное условие. Цикл for также называют циклом c предусловием. Лучше использовать цикл for, если количество итераций известно заранее.
|
|
range()
Мы используем встроенную функцию Python range. Функция range создаст список длинной в «n» элементов. В Python версии 2.Х существует другая функция под названием xrange, которая является генератором чисел и не такая ресурсоемкая, как range. Ранее разработчики сменили xrange на range в Python 3. Вот пример:
|
|
Как вы видите, функция range взяла целое число и вернула объект range. Функция range также принимает начальное значение, конечное значение и значение шага. Вот еще два примера:
|
|
В пером примере показано, что вы можете передать начальное и конечное значение, и функция range вернет числа, начиная с начального значения вплоть до (но не включая) последнее значение. Например, при запросе 5-10 мы получим 5-9. Во втором примере видно, как использовать функцию списка (list) для того, чтобы функция range вернула каждый второй элемент, между 1 и 10. Так что она начинает с 1, пропускает 2 и так далее. Теперь вы, наверное, гадаете, что же именно она будет делать с циклами? Что-ж, есть один простой способ показать, как работает цикл с использованием функции range! Давайте взглянем:
|
|
Что здесь произошло? Давайте почитаем слева на право, чтобы понять это. Для каждого числа в диапазоне 5 мы вводим число. Мы знаем, что если мы вызываем range со значением 5, мы получим список из 5 элементов. Так что каждый раз, проходя через цикл, она выводит каждый из элементов. Цикл for, показанный выше, может быть эквивалентом следующего:
|
|
Мы попробуем применить цикл в функции range, но нам нужно вывести только целые числа. Чтобы сделать это, нам нужно использовать условный оператор вместо параметра шага range. Это можно сделать следующим образом:
|
|
Вы наверное гадаете, что вообще здесь происходит? Что еще за знак процента? В Python, % называется оператором модуля. Когда вы используете оператор модуля, он возвращает остаток. Когда вы делите целое число на два, вы получаете число без остатка, так что мы выводим эти числа. Вам, возможно, не захочется использовать оператор модуля часто в будущем, но в моей работе он нередко помогает. Теперь мы можем взглянуть на цикл while.
Словари
Функция range лишь делает результат несколько меньшим. Цикл for может обходить любой итератор Python. Мы уже видели, как именно он может работать со списком. Давайте взглянем, может ли он выполнять итерацию со словарем.
|
|
Когда вы используете for в словаре, вы увидите, что он автоматически перебирает ключи. Вам не нужно указывать ключ for в a_dict.keys() (впрочем, это также работает). Python делает только нужные нам вещи. Вы возможно думаете, почему ключи выводятся в другом порядке, отличном от того, какой был указан в словаре? Как мы знаем из соответствующей статьи, словари не упорядочены, так что мы можем выполнять итерацию над ними, при этом ключи могут быть в любом порядке. Теперь, зная, что ключи могут быть отсортированы, вы можете отсортировать их до итерации. Давайте немного изменим словарь, чтобы увидеть, как это работает.
|
|
Давайте остановимся и разберемся с тем, что делает этот код. Во-первых, мы создали словарь, в котором ключи выступают в качестве целых чисел, вместо строк. Далее, мы извлекли ключи из словаря. Каждый раз, когда вы взываете метод keys(), он возвращает неупорядоченный список ключей. Если вы выведите их, и увидите, что они расположен в порядке по возрастанию, то это просто случайность. Теперь у нас есть доступ к ключам словаря, которые хранятся в переменной, под названием keys. Мы сортируем наш список, после чего используем цикл for в нем. Теперь мы готовы к тому, чтобы сделать все немного интереснее.
Оператор continue
Оператор continue начинает следующий проход цикла, минуя оставшееся тело цикла (for или while)
|
|
Оператор break
Оператор break досрочно прерывает цикл.
|
|
Волшебное слово else
Слово else, примененное в цикле for или while, проверяет, был ли произведен выход из цикла инструкцией break, или же “естественным” образом. Блок инструкций внутри else выполнится только в том случае, если выход из цикла произошел без помощи break.
|
|
- Оператор Python continue используется для пропуска выполнения текущей итерации цикла.
- Мы не можем использовать его вне цикла, он выдаст ошибку как «SyntaxError: ‘continue’ external loop».
- Мы можем использовать его с циклами for и while.
- Присутствует во вложенном цикле, он пропускает выполнение только внутреннего цикла.
- «Continue» — зарезервированное ключевое слово в Python.
- Как правило, оператор continue используется с оператором if, чтобы определить условие пропуска текущего выполнения цикла.
Синтаксис оператора
Синтаксис оператора continue:
continue
Мы не можем использовать какие-либо опции, метки или условия.
Примеры
Давайте посмотрим на несколько примеров использования оператора continue в Python.
1. Как продолжить цикл for?
Допустим, у нас есть последовательность целых чисел. Мы должны пропустить обработку, если значение равно 3. Мы можем реализовать этот сценарий, используя цикл for и оператор continue.
t_ints = (1, 2, 3, 4, 5) for i in t_ints: if i == 3: continue print(f'Processing integer {i}') print("Done")
Вывод:
2. Совместно с циклом while
Вот простой пример использования оператора continue с циклом while.
count = 10 while count > 0: if count % 3 == 0: count -= 1 continue print(f'Processing Number {count}') count -= 1
Вывод:
3. Пример с вложенным циклом
Допустим, у нас есть список кортежей для обработки. Кортеж содержит целые числа. Обработку следует пропустить при следующих условиях.
- пропустить обработку кортежа, если его размер больше 2.
- пропустить выполнение, если целое число равно 3.
Мы можем реализовать эту логику с помощью вложенных циклов for. Нам нужно будет использовать два оператора continue для выполнения вышеуказанных условий.
list_of_tuples = [(1, 2), (3, 4), (5, 6, 7)] for t in list_of_tuples: # don't process tuple with more than 2 elements if len(t) > 2: continue for i in t: # don't process if the tuple element value is 3 if i == 3: continue print(f'Processing {i}')
Вывод:
Многие популярные языки программирования поддерживают помеченный оператор continue. В основном он используется для пропуска итерации внешнего цикла в случае вложенных циклов. Однако Python не поддерживает помеченный оператор continue.
PEP 3136 был сделан, чтобы добавить поддержку метки для оператора continue. Но он был отклонен, потому что это очень редкий сценарий, который добавит ненужной сложности языку. Мы всегда можем написать условие во внешнем цикле, чтобы пропустить текущее выполнение.
Оператор break
- Оператор break в Python используется для выхода из текущего цикла.
- Мы не можем использовать оператор break вне цикла, он выдаст ошибку как «SyntaxError: ‘break’ external loop».
- Мы можем использовать его с циклами for и while.
- Если оператор break присутствует во вложенном цикле, он завершает внутренний цикл.
- «Break» — зарезервированное ключевое слово в Python.
Блок-схема оператора break
Синтаксис оператора break
Синтаксис оператора break:
break
Мы не можем использовать какие-либо опции, метки или условия.
Примеры
1. оператор break с циклом for
Допустим, у нас есть последовательность целых чисел. Мы должны обрабатывать элементы последовательности один за другим. Если мы встречаем «3», то обработка должна быть остановлена. Мы можем использовать цикл for для итерации и оператор break с условием if, чтобы реализовать это.
t_ints = (1, 2, 3, 4, 5) for i in t_ints: if i == 3: break print(f'Processing {i}') print("Done")
Вывод:
2. Оператор break с циклом while
count = 10 while count > 0: print(count) if count == 5: break count -= 1
Вывод:
3. С вложенным циклом
Вот пример оператора break во вложенном цикле.
list_of_tuples = [(1, 2), (3, 4), (5, 6)] for t in list_of_tuples: for i in t: if i == 3: break print(f'Processing {i}')
Вывод:
Однако Python не поддерживает помеченный оператор break. Он был убран, потому что это добавит ненужной сложности языку. Для этого сценария есть лучшая альтернатива — переместите код в функцию и добавьте оператор return.
In this article, you will learn how to use the break
, continue
and pass
statements when working with loops in Python. We use break, continue statements to alter the loop’s execution in a certain manner.
Statement | Description |
---|---|
break |
Terminate the current loop. Use the break statement to come out of the loop instantly. |
continue |
Skip the current iteration of a loop and move to the next iteration |
pass |
Do nothing. Ignore the condition in which it occurred and proceed to run the program as usual |
The break
and continue
statements are part of a control flow statements that helps you to understand the basics of Python.
Table of contents
- Break Statement in Python
- Example: Break for loop in Python
- How break statement works
- Example: Break while loop
- Break Nested Loop in Python
- Break Outer loop in Python
- Continue Statement in Python
- Example: continue statement in for loop
- How continue statement works
- Example: continue statement in while loop
- Continue Statement in Nested Loop
- Continue Statement in Outer loop
- Pass Statement in Python
Break Statement in Python
The break
statement is used inside the loop to exit out of the loop. In Python, when a break
statement is encountered inside a loop, the loop is immediately terminated, and the program control transfer to the next statement following the loop.
In simple words, A break
keyword terminates the loop containing it. If the break
statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.
For example, you are searching a specific email inside a file. You started reading a file line by line using a loop. When you found an email, you can stop the loop using the break statement.
We can use Python break
statement in both for loop and while loop. It is helpful to terminate the loop as soon as the condition is fulfilled instead of doing the remaining iterations. It reduces execution time.
Syntax of break
:
break
Let us see the usage of the break
statement with an example.
Example: Break for loop in Python
In this example, we will iterate numbers from a list using a for loop, and if we found a number greater than 100, we will break the loop.
Use the if condition to terminate the loop. If the condition evaluates to true, then the loop will terminate. Else loop will continue to work until the main loop condition is true.
numbers = [10, 40, 120, 230]
for i in numbers:
if i > 100:
break
print('current number', i)
Output:
curret number 10 curret number 40
Note: As you can see in the output, we got numbers less than 100 because we used the break
statement inside the if condition (the number is greater than 100) to terminate the loop
How break statement works
We used a break
statement along with if statement. Whenever a specific condition occurs and a break
statement is encountered inside a loop, the loop is immediately terminated, and the program control transfer to the next statement following the loop.
Let’s understand the above example iteration by iteration.
- In the first iteration of the loop, 10 gets printed, and the condition
i > 100
is checked. Since the value of variablei
is 10, the condition becomes false. - In the second iteration of the loop, 20 gets printed again, and the condition
i > 100
is checked. Since the value ofi
is 40, the condition becomes false. - In the third iteration of the loop, the condition
i > 100
becomes true, and thebreak
statement terminates the loop
Example: Break while loop
We can use the break
statement inside a while loop using the same approach.
Write a while loop to display each character from a string and if a character is a space then terminate the loop.
Use the if condition to stop the while loop. If the current character is space then the condition evaluates to true, then the break
statement will execute and the loop will terminate. Else loop will continue to work until the main loop condition is true.
name = 'Jesaa29 Roy'
size = len(name)
i = 0
# iterate loop till the last character
while i < size:
# break loop if current character is space
if name[i].isspace():
break
# print current character
print(name[i], end=' ')
i = i + 1
Break Nested Loop in Python
To terminate the nested loop, use a break
statement inside the inner loop. Let’s see the example.
In the following example, we have two loops, the outer loop, and the inner loop. The outer for loop iterates the first 10 numbers using the range() function, and the internal loop prints the multiplication table of each number.
But if the current number of both the outer loop and the inner loop is greater than 5 then terminate the inner loop using the break statement.
Example: Break nested loop
for i in range(1, 11):
print('Multiplication table of', i)
for j in range(1, 11):
# condition to break inner loop
if i > 5 and j > 5:
break
print(i * j, end=' ')
print('')
Break Outer loop in Python
To terminate the outside loop, use a break
statement inside the outer loop. Let’s see the example.
In the following example, we have two loops, the outer loop, and the inner loop. The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.
But if the current number of the outer loop is greater than 5 then terminate the outer loop using the break
statement.
Example: Break outer loop
for i in range(1, 11):
# condition to break outer loop
if i > 5:
break
print('Multiplication table of', i)
for j in range(1, 11):
print(i * j, end=' ')
print('')
Continue Statement in Python
The continue
statement skip the current iteration and move to the next iteration. In Python, when the continue
statement is encountered inside the loop, it skips all the statements below it and immediately jumps to the next iteration.
In simple words, the continue
statement is used inside loops. Whenever the continue
statement is encountered inside a loop, control directly jumps to the start of the loop for the next iteration, skipping the rest of the code present inside the loop’s body for the current iteration.
In some situations, it is helpful to skip executing some statement inside a loop’s body if a particular condition occurs and directly move to the next iteration.
Syntax of continue
:
continue
Let us see the use of the continue
statement with an example.
Example: continue statement in for loop
In this example, we will iterate numbers from a list using a for loop and calculate its square. If we found a number greater than 10, we will not calculate its square and directly jump to the next number.
Use the if condition with the continue
statement. If the condition evaluates to true, then the loop will move to the next iteration.
numbers = [2, 3, 11, 7]
for i in numbers:
print('Current Number is', i)
# skip below statement if number is greater than 10
if i > 10:
continue
square = i * i
print('Square of a current number is', square)
Output:
Current Number is 2
Square of a current number is 4
Current Number is 3
Square of a current number is 9
Current Number is 11
Current Number is 7
Square of a current number is 49
Note: As you can see in the output, we got square of 2, 3, and 7, but the loop ignored number 11 because we used the if condition to check if the number is greater than ten, and the condition evaluated to true, then loop skipped calculating the square of 11 and moved to the next number.
How continue statement works
We used the continue
statement along with the if statement. Whenever a specific condition occurs and the continue
statement is encountered inside a loop, the loop immediately skips the remeaning body and move to the next iteration.
Let’s understand the above example iteration by iteration.
- In the first iteration of the loop, 4 gets printed, and the condition
i > 10
is checked. Since the value ofi
is 2, the condition becomes false. - In the second iteration of the loop, 9 gets printed, and the condition
i > 10
is checked. Since the value ofi
is 9, the condition becomes false. - In the third iteration of the loop, the condition
i > 10
becomes true, and thecontinue
statement skips the remaining statements and moves to the next iteration of the loop - In the second iteration of the loop, 49 gets printed, and the condition
i > 10
is checked. Since the value ofi
is 7, the condition becomes false.
Example: continue statement in while loop
We can also use the continue
statement inside a while loop. Let’s understand this with an example.
Write a while loop to display each character from a string and if a character is a space, then don’t display it and move to the next character.
Use the if condition with the continue
statement to jump to the next iteration. If the current character is space, then the condition evaluates to true, then the continue
statement will execute, and the loop will move to the next iteration by skipping the remeaning body.
name = 'Je sa a'
size = len(name)
i = -1
# iterate loop till the last character
while i < size - 1:
i = i + 1
# skip loop body if current character is space
if name[i].isspace():
continue
# print current character
print(name[i], end=' ')
Output:
J e s a a
Continue Statement in Nested Loop
To skip the current iteration of the nested loop, use the continue
statement inside the body of the inner loop. Let’s see the example.
In the following example, we have the outer loop and the inner loop. The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.
But if the current number of the inner loop is equal to 5, then skip the current iteration and move to the next iteration of the inner loop using the continue
statement.
Example: continue statement in nested loop
for i in range(1, 11):
print('Multiplication table of', i)
for j in range(1, 11):
# condition to skip current iteration
if j == 5:
continue
print(i * j, end=' ')
print('')
Continue Statement in Outer loop
To skip the current iteration of an outside loop, use the continue
statement inside the outer loop. Let’s see the example
In the following example, The outer loop iterates the first 10 numbers, and the internal loop prints the multiplication table of each number.
But if the current number of the outer loop is even, then skip the current iteration of the outer loop and move to the next iteration.
Note: If we skip the current iteration of an outer loop, the inner loop will not be executed for that iteration because the inner loop is part of the body of an outer loop.
Example: continue
statement in outer loop
for i in range(1, 11):
# condition to skip iteration
# Don't print multiplication table of even numbers
if i % 2 == 0:
continue
print('Multiplication table of', i)
for j in range(1, 11):
print(i * j, end=' ')
print('')
Pass Statement in Python
The pass
is the keyword In Python, which won’t do anything. Sometimes there is a situation in programming where we need to define a syntactically empty block. We can define that block with the pass keyword.
A pass
statement is a Python null statement. When the interpreter finds a pass statement in the program, it returns no operation. Nothing happens when the pass
statement is executed.
It is useful in a situation where we are implementing new methods or also in exception handling. It plays a role like a placeholder.
Syntax of pass
statement:
for element in sequence:
if condition:
pass
Example
months = ['January', 'June', 'March', 'April']
for mon in months:
pass
print(months)
Output
['January', 'June', 'March', 'April']