Open In App

Loops and Control Statements (continue, break and pass) in Python

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python programming language provides the following types of loops to handle looping requirements.

Python While Loop

Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false.

Syntax of Python While

while expression:
    statement(s)

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. 

Python3




# prints Hello Geek 3 Times
count = 0
while (count < 3):   
    count = count+1
    print("Hello Geek")


Output:

Hello Geek
Hello Geek
Hello Geek

See this for an example where a while loop is used for iterators. As mentioned in the article, it is not recommended to use a while loop for iterators in python.  

Python for Loop

In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is a “for in” loop which is similar to for each loop in other languages. 

Syntax of Python for Loop

for iterator_var in sequence:
    statements(s)

It can be used to iterate over iterators and a range. 

Python3




# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
    print(i)
     
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
    print(i)
     
# Iterating over a String
print("\nString Iteration")   
s = "Geeks"
for i in s :
    print(i)
     
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
    print("%s %d" %(i, d[i]))


Output:

List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345

Time complexity: O(n), where n is the number of elements in the iterable (list, tuple, string, or dictionary).
Auxiliary space: O(1), as the space used by the program does not depend on the size of the iterable.

We can use a for-in loop for user-defined iterators. See this for example.  

Python Nested Loops

Python programming language allows using one loop inside another loop. The following section shows a few examples to illustrate the concept. 

Syntax of Python Nested for Loop

The syntax for a nested for loop statement in Python programming language is as follows:

for iterator_var in sequence:
    for iterator_var in sequence:
        statements(s)
        statements(s)

Syntax of Python Nested while Loop

The syntax for a nested while loop statement in Python programming language is as follows:

while expression:
    while expression: 
        statement(s)
        statement(s)

A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. 

Python3




from __future__ import print_function
for i in range(1, 5):
    for j in range(i):
        print(i, end=' ')
    print()


Output:

1
2 2
3 3 3
4 4 4 4

Python Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. 

Python Continue  

It returns the control to the beginning of the loop. 

Python3




# Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks':
    if letter == 'e' or letter == 's':
        continue
    print('Current Letter :', letter)


Output:

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Python Break  

It brings control out of the loop.

Python3




for letter in 'geeksforgeeks':
 
    # break the loop as soon it sees 'e'
    # or 's'
    if letter == 'e' or letter == 's':
        break
print('Current Letter :', letter)


Output:

Current Letter : e

Python Pass  

We use pass statements to write empty loops. Pass is also used for empty control statements, functions, and classes. 

Python3




# An empty loop
for letter in 'geeksforgeeks':
    pass
print('Last Letter :', letter)


Output:

Last Letter : s

Exercise: How to print a list in reverse order (from last to the first item) using while and for-in loops.



Previous Article
Next Article

Similar Reads

Difference between continue and pass statements in Python
Using loops in Python automates and repeats the tasks in an efficient manner. 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. Loop control statements change execution from its normal sequence. When execution leaves a scop
3 min read
break, continue and pass in Python
Using loops in Python automates and repeats the tasks in an efficient manner. 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. Loop control statements change execution from their normal sequence. When execution leaves a sc
5 min read
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause t
7 min read
Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
Python If Else Statements - Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determin
8 min read
How to Break out of multiple loops in Python ?
In this article, we will see how to break out of multiple loops in Python. For example, we are given a list of lists arr and an integer x. The task is to iterate through each nested list in order and keep displaying the elements until an element equal to x is found. If such an element is found, an appropriate message is displayed and the code must
6 min read
Python Continue Statement
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 StatementPython 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 i
4 min read
Python EasyGUI – Continue Cancel Box
Continue Cancel Box : It is used to display a window having a two option continue or cancel in EasyGUI, it can be used where there is a need to display two option continue or cancel for example when we want to confirm the option if continue is pressed application will move forward else it will get terminated, below is how the continue cancel box lo
3 min read
PyQt5 QCalendarWidget - Continue functions by enabling
In this article, we will see how we can continue the functions of the QCalendarWidget. Stopping function means that the QCalendarWidget will not be able to do a single thing like selection changing date etc. Disabling the calendar do not delete or hide the widget from the screen. Disabling is used to stop the user from doing any changes on it, but
2 min read
Output of Python Programs | Set 22 (Loops)
Prerequisite: Loops Note: Output of all these programs is tested on Python3 1. What is the output of the following? mylist = ['geeks', 'forgeeks'] for i in mylist: i.upper() print(mylist) [‘GEEKS’, ‘FORGEEKS’]. [‘geeks’, ‘forgeeks’]. [None, None]. Unexpected Output: 2. [‘geeks’, ‘forgeeks’] Explanation: The function upper() does not modify a string
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg