Search

What Are Break and Continue Statements in Python

In this article, you will learn about the Loop control statement, the necessity of using these statements to control the loop's flow, and their use according to our requirements.The Article has been organized in the following manner: Introduction to Loop Control Statement Break statement Syntax of break statement Flow diagram and steps involved Example of break statement Continue Statement Syntax of continue statement Flow diagram and steps involved Example of continue statement Pass statement Syntax of pass statement Example of Pass statement Difference between break and continue statement Conclusion Introduction to Loop Control Statement:  Break and Continue statements are also known as Loop Control Statements, as they automate the working of the inner loop. Loop automates the task and repeats in a certain manner, but there are some special cases where we need to terminate the loop or skip some iteration. There we use a Loop Control Statement that is Break and Continue.Python supports 3 basic Loop Control Statements Break Statement Continue Statement Pass Statement Break Statement:  It works similar to a break statement in C. It terminates the current working loop and passes the control to the next statement, and if the break statement resides inside the nested loop, it passes control to the outer loop. It can be used with both while and for loops. Forms of break statement:Labelled break statement Unlabelled break statement Labelled break statement: It terminates the loop's outer statement, which has been marked with the given label.Unlabelled break statement: It terminates the innermost statement of the loopUses of break statement: It is used when we want to skip or terminate a certain statement. When some external condition is triggered, and it requires the termination of the loop.Syntax: breakFlow diagram of break statement:Here are the steps involved in the flow chart given above explaining a break statement:  Execution of loop statement begins.  If the looping statement is true, iteration starts. If the looping statement contains a break statement, the iteration will terminate, and then the current loop will exit. When the condition completes its execution, it will return its output. If the looping statement is false, it will exit from the loop. End of the loop. Example: Let's consider the condition where we want to iterate a loop from 1 to 10.  When 6 is encountered, we want to break the loop and return to the outer condition. Here we use break statement with for loop and if statement. #Demonstration of Python break statement #using for loop #loop from 0 to 9 for i in range(10):        # if i is equal to 6        # break statement terminate the current working loop          if i == 6:              break        else:               print (i)Output:  0   1   2   3   4   5 Continue Statement:  It is the second form of the Loop Control Statement, very similar to the break statement. But when it comes to the working of the continue statement, it works just opposite to the break statement. Instead of terminating certain conditions, it jumps off to the very next condition. But it will continue the execution of the loop statement as per its name. Forms of continue statement: Labelled continue statement Unlabelled continue statement Labelled continue statement: It skips the iteration of the outermost loop, marked with the label. Unlabelled continue statement: It skips the iteration of the innermost loop. Uses of Continue statement: When we don’t want certain conditions to run. When we don’t want to terminate the loop and just want to skip iteration. When we want to continue the iteration. Syntax : continueFlow diagram of continue statement:Here are the steps involved in the flow chart given above explaining a continue statement: Execution of loop statement begins.  If the looping statement is true, iteration starts. If the looping statement contains a continue statement, the iteration will skip the condition statement and then jump to the next iteration statement. When the condition completes its execution, it will return its output. If the looping statement is false, it will exit from the loop. End of the loop. Example:  The continue statement is used in the program to skip any iteration, such as when we don't want to print a certain statement. Consider the example of a break statement altering the condition. There are numbers from 1 to 10, but we don't want 2 to come and we don't want to increase the number of looping statements in our program either. For this we should use a continue statement. Refer to the below implementation:#Demonstration of Python continue statement #using for loop #loop from 0 to 9 for i in range(10):        # if i is equal to 2        # continue statement will skip          #and start executing next iteration        if i == 2:              continue         else:               print (i)Output: 0   1   3   4   5   6   7   8   9  Pass statement:  Pass statement is not found in traditional C language; it works like a null operation because nothing happens when the pass statement is executed. It is used in Python when any statement is required syntactically, but we don't want any command or code lines to be executed.Pass statement is also known as the placeholder, which can be used inside the function call, classes, and lopping or control statement.  It can be used as a declarative statement, which can be implemented later on when required. It is just a block of code that runs when called and works the same as the null statement. The best place to use the pass statement is Stubs. Uses of Pass Statement: It can be used in Stubs. It can be used while writing empty loops. It can be used for empty control statements. It can also be used to implement empty functions and classes. Syntax: passExample:#Demonstration of Python pass statement  #using for loop  #loop from 0 to 9  for i in range(10):              # if i is equal to 6         # pass statement will execute          #but there will be no impact          #on the looping statement          if i == 6:               pass               print ‘Just a pass statement’         else:                print (i) Output: 0 1 2 3 4 5 Just a pass statement 7 8 9Difference between break and continue statement:  The main difference between both the statements is that when break keyword comes, it terminates the execution of the current loop and passes the control over the next loop or main body, whereas when continue keyword is encountered, it skips the current iteration and executes the very next iteration in the loop. In simple words break statement leaves a loop, whereas the continue statement jumps to the next iteration. Conclusion: These are the loop control statements, which help us to terminate or skip some required statement under the normal procedure. Every statement has its function, and none of them can be considered to be better than the other, as they each have different aspects and usage. 

What Are Break and Continue Statements in Python

10K
  • by Abhresh S
  • 23rd Mar, 2021
  • Last updated on 24th Mar, 2021
  • 5 mins read
What Are Break and Continue Statements in Python

In this article, you will learn about the Loop control statement, the necessity of using these statements to control the loop's flow, and their use according to our requirements.

The Article has been organized in the following manner: 

  • Introduction to Loop Control Statement 
  • Break statement 
  • Syntax of break statement 
  • Flow diagram and steps involved 
  • Example of break statement 
  • Continue Statement 
  • Syntax of continue statement 
  • Flow diagram and steps involved 
  • Example of continue statement 
  • Pass statement 
  • Syntax of pass statement 
  • Example of Pass statement 
  • Difference between break and continue statement 
  • Conclusion 

Introduction to Loop Control Statement 

Break and Continue statements are also known as Loop Control Statements, as they automate the working of the inner loop. Loop automates the task and repeats in a certain manner, but there are some special cases where we need to terminate the loop or skip some iteration. There we use Loop Control Statement that is Break and Continue.

Python supports 3 basic Loop Control Statements 

  • Break Statement 
  • Continue Statement 
  • Pass Statement 

Break Statement:  

It works similar to a break statement in C. It terminates the current working loop and passes the control to the next statement, and if the break statement resides inside the nested loop, it passes control to the outer loop. It can be used with both while and for loops. 

Forms of break statement:

  1. Labelled break statement 
  2. Unlabelled break statement 

Labelled break statement: It terminates the loop's outer statement, which has been marked with the given label.

Unlabelled break statement: It terminates the innermost statement of the loop

Uses of break statement: 

  • It is used when we want to skip or terminate a certain statement. 
  • When some external condition is triggered, and it requires the termination of the loop.
Syntax: break

Flow diagram of break statement:


Flow diagram of break statement

Here are the steps involved in the flow chart given above explaining a break statement 

  1. Execution of loop statement begins 
  2. If the looping statement is true, iteration starts. 
  3. If the looping statement contains a break statement, the iteration will terminate, and then the current loop will exit. 
  4. When the condition completes its execution, it will return its output. 
  5. If the looping statement is false, it will exit from the loop. 
  6. End of the loop. 

Example: 

Let's consider the condition where we want to iterate a loop from 1 to 10 When 6 is encountered, we want to break the loop and return to the outer condition. Here we use break statement with for loop and if statement. 

#Demonstration of Python break statement 
#using for loop 
#loop from 0 to 9 
for i in range(10): 
       # if i is equal to 6 
       # break statement terminate the current working loop   
       if i == 6: 
             break 
       else: 
              print (i)

Output:  

 
1  
2  
3  
4  
5 

Continue Statement:  

It is the second form of the Loop Control Statement, very similar to the break statement. But when it comes to the working of the continue statement, it works just opposite to the break statement. Instead of terminating certain conditions, it jumps off to the very next condition. But it will continue the execution of the loop statement as per its name. 

Forms of continue statement: 

  1. Labelled continue statement 
  2. Unlabelled continue statement 

Labelled continue statement: It skips the iteration of the outermost loop, marked with the label. 

Unlabelled continue statement: It skips the iteration of the innermost loop. 

Uses of Continue statement: 

  • When we don’t want certain conditions to run. 
  • When we don’t want to terminate the loop and just want to skip iteration. 
  • When we want to continue the iteration. 
Syntax : continue

Flow diagram of continue statement:Flow diagram of continue statement

Here are the steps involved in the flow chart given above explaining a continue statement: 

  1. Execution of loop statement begins 
  2. If the looping statement is true, iteration starts. 
  3. If the looping statement contains a continue statement, the iteration will skip the condition statement and then jump to the next iteration statement. 
  4. When the condition completes its execution, it will return its output. 
  5. If the looping statement is false, it will exit from the loop. 
  6. End of the loop. 

Example:  

The continue statement is used in the program to skip any iteration, such as when we don't want to print a certain statement. Consider the example of a break statement altering the condition. There are numbers from 1 to 10, but we don't want 2 to come and we don't want to increase the number of looping statements in our program either. For this we should use a continue statement. 

Refer to the below implementation:

#Demonstration of Python continue statement 
#using for loop 
#loop from 0 to 9 
for i in range(10): 
       # if i is equal to 2 
       # continue statement will skip   
       #and start executing next iteration 
       if i == 2: 
             continue 
        else: 
              print (i)

Output: 

 
 
 
 
 
 
 
 
 

Pass statement:  

Pass statement is not found in traditional C language; it works like a null operation because nothing happens when the pass statement is executed. It is used in Python when any statement is required syntactically, but we don't want any command or code lines to be executed.

  • Pass statement is also known as the placeholder, which can be used inside the function call, classes, and lopping or control statement.  
  • It can be used as a declarative statement, which can be implemented later on when required. 
  • It is just a block of code that runs when called and works the same as the null statement. 
  • The best place to use the pass statement is Stubs. 

Uses of Pass Statement: 

  • It can be used in Stubs. 
  • It can be used while writing empty loops. 
  • It can be used for empty control statements. 
  • It can also be used to implement empty functions and classes. 
Syntax: pass

Example:

#Demonstration of Python pass statement 
#using for loop 
#loop from 0 to 9 
for i in range(10):      
       # if i is equal to 6 
       # pass statement will execute  
       #but there will be no impact  
       #on the looping statement  
       if i == 6: 
             pass 
             print ‘Just a pass statement’ 
       else: 
              print (i) 

Output:

0 
1 
2 
3 
4 
5 
Just a pass statement 
7 
8 
9

Difference between break and continue statement:  

  • The main difference between both the statements is that when break keyword comes, it terminates the execution of the current loop and passes the control over the next loop or main body, whereas when continue keyword is encountered, it skips the current iteration and executes the very next iteration in the loop. 
  • In simple words break statement leaves a loop, whereas the continue statement jumps to the next iteration. 

Conclusion: 

These are the loop control statements, which help us to terminate or skip some required statement under the normal procedure. Every statement has its function, and none of them can be considered to be better than the other, as they each have different aspects and usage. 

Abhresh

Abhresh S

Freelance Corporate Trainer

An Online Technical Trainer by profession! And Content writer by hobby! Interested in sharing quality knowledge to make the Industry grow better towards better success and better tomorrow! With a Guru Mantra of - "Keep Learning & Keep Practicing".

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable language” and it means that Scala grows with you. In recent times, Scala has attracted developers because it has enabled them to deliver things faster with fewer codes. Developers are now much more interested in having Scala training to excel in the big data field. The Scala community has grown over the years and it has now become a standard for enterprise, start-ups and universities alike. Scala is now being used by many companies and individuals to build their own new ideas. Play Framework, Akka, Apache Spark, etc are some of the tools and projects created using Scala. Scala is now the next wave of computation engines and more importance has been given to the speed processing rather than the size of the batch, and the ability to process event streaming in real-time. 1.Apache Spark Apache Spark can be considered as the replacement of MapReduce. In late 2013, Cloudera, the largest Hadoop vendor supported the idea of replacing MapReduce with Apache Spark. Spark is developed by AMPLab and it is a fast and general purpose engine for large-scale data processing. Spark effectively provides an alternative for Hadoop’s two stage MapReduce model. It has improved the performance of certain applications to 100 times with its fine grain operators, in-memory caching of intermediate data, and data flow optimization. 2. Scalding Scalding has been introduced and maintained by Twitter. It provides full benefits of Scala syntax and functional operations. Scala is a powerful language for solving functional problems. Scalding makes comprehensive use of Scala and it is an extension to cascading that enables application development with Scala. If we focus on the benefits of Scalding, data applications can be built with Scala. With simple and concise syntax code becomes easier to interpret. Scalding has filled the benefits of cascading application framework. 3. Apache Kafka Built and maintained by LinkedIn, Apache Kafka is a distributed streaming platform. Apache Kafka allows the user to publish and subscribe streams of data, just like a messaging system. Kafka is responsible for handling hundred of megabytes of read-write traffic per second from thousand of clients. It is also empowered by Scala and we can see the influence of the language. Real-time data pipelines and streaming apps can be built by using Apache Kafka. Yahoo Kafka Manager is also written in Scala and the web console is built using Play Framework. The Kafka Manager is being used by many teams including the Media Analytics team. It interacts with an actor-based, in-memory model built with Akka and Apache Curator. 4. Finagle Built by the people at twitter, Finagle can be considered as one of the best case using Scala. It is used to build high-concurrency servers and is an extensible RPC system for JVM. Finagle was intended to provide high performance, concurrency along with Scala and Java idiomatic APIs. Finagle is known for the optimal use of available system resources and high scalability through concurrency. It uses safe, simple and clean concurrent programming model which is based on Futures. All these results in safe and modular programs.
Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable languag... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
3965
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More

IOS Application Development Guide

Developing applications have never been easy task for developers. Mobile applications industry is becoming huge and it will keep on expanding. iOS applications are actually somewhat different from android applications. Programmers starting off with iOS application development should be familiar with the basics of the Apple’s development tools. Proper iOS training will give better idea of what you can and can’t do before starting off. Here we guide you in a right way for iOS development and how to do. We provide you the languages that has to be known before developing an iOS application, details on coding environment and the Apple’s guidelines which has to be followed. Where do you start? In order to do a graphical interface for your apps, you will have to know Xcode. Xcode is the Integrated Development Environment(IDE) for Mac and iOS. Xcode is free to download from the Apple site. You are not limited to a particular language while developing apps for iOS. There are many places for you to get started, consider Apple’s own guide which helps you out in Xcode, structuring and implementing your apps and finally uploading it to the App Store. You get to know about everything under one roof here. Apple also has videos which include various parts of development. These videos are from WWDC and you will get to know tricks and tips direct from the company. You can watch the videos here. If you are looking for some places other than the official sites, then Code School offers you free iOS course which is separated into different levels and you will even earn a Course Completion Badge at the end of course. Get started for free here. You can even try raywenderlich tutorials for iOS. Following Guidelines while developing apps Following these App Store Review Guidelines will help you to develop an app which will meet the standards set by Apple. Now these guidelines are very specific as we all know the quality of apps available in the App Store. At times you might even find it tedious to follow all of these guidelines, but even if your app does not meet them even remotely, chances are that your app might be rejected during the review process. Apple has also stated some top reasons for your app to get rejected. The review of the app will be done based on some factors like app design, content, and technical details. The app might also get rejected if any controversial subject is involved. Now these might be difficult for beginners or sometimes even for professional developers, but it is better to follow these guidelines rather than getting rejected. There are even some more guidelines to follow if you are going to integrate additional functions with your app such as Apple pay. Many of the Apple API’s have their own guidelines and it is better that you are clear of this before developing your apps. iOS Application Design Guidelines Apple has a set of design and interface guidelines. To maintain its legacy, Apple wants all the apps in their store to be designed in the same way. By designing it, in the same way, means that applications should use the same basic UI elements. “The world’s most advanced mobile OS offers everything you need to design beautiful, engaging apps that radiate power and simplicity”, says Apple. Apple has provided Human Interface Guidelines page and it contains all the basics that developers will look for in both apps and icon designs. To start off with the iOS app development, Apple has also provided a set of Do’s and Don’ts that make it easier for the developers. Github and testing codes Creating a bug-free application is a myth. Applications in their early release have some bugs and it is good practices to get other people sees your code and invite beta testers to try your app. GitHub is the place for software versioning and collaborative work. GitHub provides an incredible way of linking Xcode into it. After registering on GitHub, the work done on it will be saved and accessible by other people on your team.
6336
IOS Application Development Guide

Developing applications have never been easy task ... Read More

20% Discount