Python Control Flow Tools
break and continue …
Introduction
Using for loops and while loops in Python allow you to automate and repeat tasks in an efficient manner.
But sometimes, an external factor may influence the way your program runs.
When this occurs, you may want your program to exit a loop completely, skip part of
a loop before continuing, or ignore that external factor. You can do these actions with break,
continue, and pass statements
break statement:
In Python, the break statement provides you with the opportunity to exit out of a loop when an
external condition is triggered.
Continue statement:
The continue statement gives you the option to skip over the part of a loop where an external
condition is triggered, but to go on to complete the rest of the loop.
Example 1 : illustrate break
Example 2: Break with numbers
Example 3: Break with a string
Example 4 : Continue with numbers
Example 5 : Continue with string
Example 6 : Break with list of words
Break the loop with a condition
Example 7 : Print cubes of numbers except 3
define range function to take 1 to 10 numbers then write if condition ,when ever it reaches 3 it skip the number and continue with the next numbers
Example 8 : Print only odd numbers from a list of numbers using continue
Above example using for loop
# list of numbers
n = [10,20,23,43,54,106]
# iterating each number in list
for i in n:
# checking condition
if i % 2 != 0:
print(i)
print odd numbers using List comprehension
# Using List comprehension
n = [10,20,23,43,54,106]
odds = [i for i in n if i % 2 != 0]
print(odds)
print odd numbers using lambda function
n = [10,20,23,43,54,106]
odds = list(filter(lambda i: (i%2 !=0 ),n))
print(odds)