Continue a Loop if a Condition is Met

Break and continue statements are used inside the loop of any programming language for different purposes. These two statements are considered as jump statements because both statements move the control from one part to another part of the script.  The break statement is used within any loop to terminate the loop based on any specific condition before the termination condition appears. The continue statement is used within any loop to omit one or more statements of the loop based on any specific condition but it is not used to terminate the loop. How these statements are used inside the python loop are shown in this tutorial.

Using a break statement:

The break statement can be used for various purposes inside any loop in Python. Some uses of break statements are shown in the following part of this tutorial using different examples.

Example-1: Terminate the infinite loop based on random number

In the following example, an integer random number will be generated within the infinite while loop. When the newly generated random value is more than 75 or equal to 99 then the break statement will be executed and terminated the loop otherwise the loop will continue for other values.

#!/usr/bin/env python3
# import randint module
from random import randint

# Define a infinite while loop
while ( True ):

# Generate a randon number from 10 to 99
number = randint( 10 , 99 )

# Print the currently generated number
print ( "The newly generated number is %s" % number)

# Terminate the loop if the number is more than 75
if (number > 75 ):
print ( "Better luck next time" )
break

# Terminate the loop if the number is equal to 99
elif (number == 99 ):
print ( "Bingo!!!, You are the winner" )
break

# Continue the loop
else:
print ( "You can try for another time" )

Output:

The following output will appear after running the script.

Example-2: Stop the iteration of a list based on a particular value

The following script will read the values from a list variable named languages by using a for loop. When the if condition inside the loop becomes true then the loop will be terminated before reading all items for the break statement.

#!/usr/bin/env python3
# Declare a list of languages
languages = [ 'Bash' , 'PHP' , 'Java' , 'Python' , 'C#' , 'C++' ]

# Print the list until the break statement is executed
print ( 'List of different languages:' )

# Iterate the list
for lname in languages:

# Print the current list item
print (lname)

# Check the condition to exit from the loop
if (lname == 'Python' ):
break

# Print the loop termination message
print ( 'Terminated from the loop' )

Output:

The following output will appear after running the script.

Example-3: Read the particular three items from a dictionary

The following example shows how you can read only three specific items from a dictionary using a break statement and for loop. A dictionary of six items is defined in the script where key contains the name of a student and the value contains the merit position of that student. The for loop is used to read the values of the dictionary and store the names of those students in a list whose merit positions are within 1 to 3. The loop will be terminated after adding three items on the list by using a break statement.

#!/usr/bin/env python3
# Define the list to store the names of the first three persons
topList = [ '' , '' , '' ]

# Set the counter value to terminate the loop
counter = 0

# Define the dictionary of six elements
meritList = { 'Mohammed': 1 , 'Mila Rahman': 5 , 'Sakib Al Hasan':3 , 'Brian Lara': 6 ,
'Sachin Tendulker': 2 , 'Alif Hossain':4 }

# Iterate the values of the dictionary to retrieve the names of first three merit persons
for student_name in meritList:

# Read the merit position
merit_pos = meritList[student_name]

# Store the index value in the list if the position is within 1 to 3 and counter by 1
if (merit_pos < 4 ):
topList[merit_pos-1 ] = student_name
counter = counter + 1

# Terminate from the loop if the counter value is 3
if (counter == 3 ):
break

# Read and print the values of the list based on the position
for n in range ( 0 , 3 ):
print ( "%s is in the position %s" %(topList[n] ,n+1 ) )

Output:

The following output will appear after running the script.

Using the continue statement:

The continue statement does not terminate the loop like a break statement. It transfers the control of the program at the top of the loop without executing some particular statements. Some uses of continue statement are shown in the following part of this tutorial using different examples.

Example-4: Print those values from a list that are divisible by 3 and 5

The following script will read a list of numbers using for loop and print those numbers from the list which are divisible by 3 and 5 by using if and continue statement.

#!/usr/bin/env python3
# Declare a list of numbers
numbers = [ 5 , 10 , 11 , 15 , 25 , 30 , 46 , 45 , 50 ]

# Print message
print ( 'Numbers divisible by 3 and 5:' )

# Iterate the list
for n in numbers:

# Check the condition to run continue statement
if (n % 3 != 0 or n % 5 != 0 ):
continue

# Print the numbers which are divisible by 3 and 5
else:
print (n)

Output:

The following output will appear after running the script.

Example-5: Print the specific values from a dictionary

A dictionary of five persons is defined in the script where the key contains the name of the person and the value of each key contains 'Present' or 'Absent' as value. The following script will print those names of the persons from the dictionary that contains the value, 'Present'.

#!/usr/bin/env python3
# Define the dictionary of 5 persons
persons = { 'Mr. Micheal': 'Present' , 'Mr. Robin': 'Absent' , 'Mrs. Ella':'Absent' ,
'Miss Lara': 'Present' , 'Mr. Hossain':'Present' }

# Print message
print ( 'The following persons are present in the meeting:' )

# Iterate the dictionary
for name in persons:
# Check the condition to run continue statement
if (persons[name] == 'Absent' ):
continue
# Print the name of the person
else:
print (name)

Output:

The following output will appear after running the script.

Conclusion:

The differences between break and continue statements within a loop are explained by using various examples in this tutorial. It will help the readers to know the uses of these statements in the loop properly.

Watch Author's Video: here

About the author

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

greenmandaunded1936.blogspot.com

Source: https://linuxhint.com/python_break_continue_loop/

0 Response to "Continue a Loop if a Condition is Met"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel