Decorator is a good approach.
from functools import wraps
import time
class retry:
def __init__(self, success=lambda r:True, times=3, delay=1, raiseexception=True, echo=True):
self.success = success
self.times = times
self.raiseexception = raiseexception
self.echo = echo
self.delay = delay
def retry(fun, *args, success=lambda r:True, times=3, delay=1, raiseexception=True, echo=True, **kwargs):
ex = Exception(f"{fun} failed.")
r = None
for i in range(times):
if i > 0:
time.sleep(delay*2**(i-1))
try:
r = fun(*args, **kwargs)
s = success(r)
except Exception as e:
s = False
ex = e
# raise e
if not s:
continue
return r
else:
if echo:
print(f"{fun} failed.", "args:", args, kwargs, "nresult: %s"%r)
if raiseexception:
raise ex
def __call__(self, fun):
@wraps(fun)
def wraper(*args, retry=0, **kwargs):
retry = retry if retry>0 else self.times
return self.__class__.retry(fun, *args,
success=self.success,
times=retry,
delay=self.delay,
raiseexception = self.raiseexception,
echo = self.echo,
**kwargs)
return wraper
some usage examples:
@retry(success=lambda x:x>3, times=4, delay=0.1)
def rf1(x=[]):
x.append(1)
print(x)
return len(x)
> rf1()
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
4
@retry(success=lambda x:x>3, times=4, delay=0.1)
def rf2(l=[], v=1):
l.append(v)
print(l)
assert len(l)>4
return len(l)
> rf2(v=2, retry=10) #overwite times=4
[2]
[2, 2]
[2, 2, 2]
[2, 2, 2, 2]
[2, 2, 2, 2, 2]
5
> retry.retry(lambda a,b:a+b, 1, 2, times=2)
3
> retry.retry(lambda a,b:a+b, 1, "2", times=2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Decorator is a good approach.
from functools import wraps
import time
class retry:
def __init__(self, success=lambda r:True, times=3, delay=1, raiseexception=True, echo=True):
self.success = success
self.times = times
self.raiseexception = raiseexception
self.echo = echo
self.delay = delay
def retry(fun, *args, success=lambda r:True, times=3, delay=1, raiseexception=True, echo=True, **kwargs):
ex = Exception(f"{fun} failed.")
r = None
for i in range(times):
if i > 0:
time.sleep(delay*2**(i-1))
try:
r = fun(*args, **kwargs)
s = success(r)
except Exception as e:
s = False
ex = e
# raise e
if not s:
continue
return r
else:
if echo:
print(f"{fun} failed.", "args:", args, kwargs, "nresult: %s"%r)
if raiseexception:
raise ex
def __call__(self, fun):
@wraps(fun)
def wraper(*args, retry=0, **kwargs):
retry = retry if retry>0 else self.times
return self.__class__.retry(fun, *args,
success=self.success,
times=retry,
delay=self.delay,
raiseexception = self.raiseexception,
echo = self.echo,
**kwargs)
return wraper
some usage examples:
@retry(success=lambda x:x>3, times=4, delay=0.1)
def rf1(x=[]):
x.append(1)
print(x)
return len(x)
> rf1()
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
4
@retry(success=lambda x:x>3, times=4, delay=0.1)
def rf2(l=[], v=1):
l.append(v)
print(l)
assert len(l)>4
return len(l)
> rf2(v=2, retry=10) #overwite times=4
[2]
[2, 2]
[2, 2, 2]
[2, 2, 2, 2]
[2, 2, 2, 2, 2]
5
> retry.retry(lambda a,b:a+b, 1, 2, times=2)
3
> retry.retry(lambda a,b:a+b, 1, "2", times=2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Put your try/except structure more in-wards. Otherwise when you get an error, it will break all the loops.
Perhaps after the first for-loop, add the try/except. Then if an error is raised, it will continue with the next file.
for infile in listing:
try:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
pass
This is a perfect example of why you should use a with statement here to open files. When you open the file using open(), but an error is catched, the file will remain open forever. Now is better than never.
for infile in listing:
try:
if infile.startswith("ABC"):
with open(infile,"r") as fo
for line in fo:
if line.startswith("REVIEW"):
print infile
except:
pass
Now if an error is caught, the file will be closed, as that is what the with statement does.
- Оператор 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.
Сегодня мы узнаем об операторах continue и break в Python. Они нужны для изменения потока цикла.
Оператор continue в Python используется для перевода управления программой в начало цикла. Оператор continue пропускает оставшиеся строки кода внутри цикла и запускает следующую итерацию. В основном он используется для определенного условия внутри цикла, чтобы мы могли пропустить конкретный код для определенного условия.
Синтаксис:
#loop statements continue #the code to be skipped
Диаграмма потока

Рассмотрим следующие примеры.
Пример 1:
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 из кода.
Давайте посмотрим на другой пример.
Пример 2:
str = "JavaTpoint"
for i in str:
if(i == 'T'):
continue
print(i)
Выход:
J a v a p o i n t
Оператор pass
Оператор pass является нулевой операцией, поскольку при ее выполнении ничего не происходит. Он используется в тех случаях, когда оператор синтаксически необходим, но мы не хотим использовать на его месте какой-либо оператор.
Например, его можно использовать при переопределении метода родительского класса в подклассе, но не нужно указывать его конкретную реализацию в подклассе.
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
Мы узнаем больше об операторе pass в следующем руководстве.
Оператор break в Python
Break – это ключевое слово в Python, которое используется для вывода управления программой из цикла. Оператор break разрывает циклы один за другим, т. е. в случае вложенных циклов сначала прерывает внутренний цикл, а затем переходит к внешним циклам. Другими словами, мы можем сказать, что break используется для прерывания текущего выполнения программы, и управление переходит к следующей строке после цикла.
Break обычно используется в тех случаях, когда нужно разорвать цикл для заданного условия.
Синтаксис разрыва приведен ниже.
#loop statements break;
Пример 1:
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
Пример 2:
str = "python"
for i in str:
if i == 'o':
break
print(i);
Выход:
p y t h
Пример 3: оператор 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
Пример 4:
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

Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
In this lesson you’ll see practical examples of the two loop interruption options you’ve learned about in the last lesson. The used examples are debugged in the video, so that you get a sense of what’s happening behind the scenes. The examples covered in this lesson are displayed below.
n = 5
while n > 0:
n = n - 1
if n == 2:
break
print(n)
print("Loop is finished")
n = 5
while n > 0:
n = n - 1
if n == 2:
continue
print(n)
print("Loop is finished")
If you’d like to explore another use case for the break statement, then check out How Can You Emulate Do-While Loops in Python? from Real Python.
00:00
All right, so let’s see how we can use these key terms. I’m going to write another while loop that was pretty similar to the original one we saw.
00:10
First, we need to initialize a variable and say n = 5. Then I’m going to write my while loop. And my condition is going to be if it’s greater than 0, then I’m going to execute the block of code below.
00:27
So, first thing we did was decrement n by 1. And now this is where I’m going to include a conditional statement, my if statement.
00:39
if n == 2: I’m actually going to break out of my block. But if it does not equal 2, then I’m going to continue on and I’m going to print n just like before.
00:59
Now, this next piece right here is going to execute once the while loop is finished normally. I’m just going to print 'Loop is finished'.
01:16
All right. So, take a minute to think about what is going to happen and then we’ll run it and see if you’re right. All right, let’s see. All right, so what I see now is that I printed those first two like I did before. I have 4 and I have 3. But whenever n… Over here we can see n is currently equal to 2, it ran into this if statement and it actually broke out of that code entirely and it went down to the first statement after the while loop, which is 'Loop is finished'.
01:51
So now I’m going to simply change this word break to continue.
02:06
Now let’s see what happens when I run this code with the word continue. All right, so we see now I have 4 and 3 still. I don’t have 2, but I did continue on and have 1 and 0.
02:22
And then once that loop was exhausted, I then printed my Loop is finished. Let’s look at this step-by-step with our debugger.
02:39
So first, we’re going to initialize our variable to 5, and I’m going to do just like I did before. 5 is greater than 0, so it returns True.
02:52
4 does not equal 2, so this returns False, so it’s not going to execute that code but it is going to go ahead and jump to the next line, which is to print n.
03:02
But this is still inside of my loop, so I’m going to then jump back up to the top of my loop and check if the condition is still True.
03:20
I’ll continue to do this until I get to 2. Now when n equals 2, this is going to return True. And if this returns True, my if statement is going to start. So if this returns True, I’m going to jump into my if statement and it says continue, so what’s going to happen is I actually jump back up to my while loop and I check my condition.
03:48
And here, I see that it’s still True, so I’m going to continue on.
03:58
And that’s why I get the 1 next and I left out 2. It was because it never actually reached the print(n).
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 > 100is checked. Since the value of variableiis 10, the condition becomes false. - In the second iteration of the loop, 20 gets printed again, and the condition
i > 100is checked. Since the value ofiis 40, the condition becomes false. - In the third iteration of the loop, the condition
i > 100becomes true, and thebreakstatement 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 > 10is checked. Since the value ofiis 2, the condition becomes false. - In the second iteration of the loop, 9 gets printed, and the condition
i > 10is checked. Since the value ofiis 9, the condition becomes false. - In the third iteration of the loop, the condition
i > 10becomes true, and thecontinuestatement 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 > 10is checked. Since the value ofiis 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']