Python programming language provides following types of loops to handle looping requirements. Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.
-
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.
Syntax :while expression: statement(s)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.
Example:# Python program to illustrate# while loopcount=0while(count <3):count=count+1print("Hello Geek")chevron_rightfilter_noneOutput:
Hello Geek Hello Geek Hello Geek
-
Using else statement with while loops: As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
If else like this:ifcondition:# execute these statementselse:# execute these statementschevron_rightfilter_noneand while loop like this are similar
whilecondition:# execute these statementselse:# execute these statementschevron_rightfilter_none#Python program to illustrate# combining else with whilecount=0while(count <3):count=count+1print("Hello Geek")else:print("In Else Block")chevron_rightfilter_noneOutput:
Hello Geek Hello Geek Hello Geek In Else Block
- Single statement while block: Just like the if block, if the while block consists of a single statement the we can declare the entire loop in a single line as shown below:
# Python program to illustrate# Single statement while blockcount=0while(count==0):print("Hello Geek")chevron_rightfilter_noneNote: It is suggested not to use this type of loops as it is a never ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.
See this for an example where while loop is used for iterators. As mentioned in the article, it is not recommended to use while loop for iterators in python.
-
Using else statement with while loops: As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed.
- for in Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence: statements(s)It can be used to iterate over iterators and a range.
# Python program to illustrate# Iterating over a listprint("List Iteration")l=["geeks","for","geeks"]foriinl:print(i)# Iterating over a tuple (immutable)print("\nTuple Iteration")t=("geeks","for","geeks")foriint:print(i)# Iterating over a Stringprint("\nString Iteration")s="Geeks"foriins :print(i)# Iterating over dictionaryprint("\nDictionary Iteration")d=dict()d['xyz']=123d['abc']=345foriind :print("%s %d"%(i, d[i]))chevron_rightfilter_noneOutput:
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
- Iterating by index of sequences: We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length.
See the below example:# Python program to illustrate# Iterating by indexlist=["geeks","for","geeks"]forindexinrange(len(list)):printlist[index]chevron_rightfilter_noneOutput:
geeks for geeks
- Using else statement with for loops: We can also combine else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution.
Below example explains how to do this:# Python program to illustrate# combining else with forlist=["geeks","for","geeks"]forindexinrange(len(list)):printlist[index]else:print"Inside Else Block"chevron_rightfilter_noneOutput:
geeks for geeks Inside Else Block
- Nested Loops: Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax:foriterator_varinsequence:foriterator_varinsequence:statements(s)statements(s)chevron_rightfilter_noneThe syntax for a nested while loop statement in Python programming language is as follows:
whileexpression:whileexpression:statement(s)statement(s)chevron_rightfilter_noneA 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.
# Python program to illustrate# nested for loops in Pythonfrom__future__importprint_functionforiinrange(1,5):forjinrange(i):print(i, end=' ')print()chevron_rightfilter_noneOutput:
1 2 2 3 3 3 4 4 4 4
- Loop Control Statements: Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
- Continue Statement: It returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'forletterin'geeksforgeeks':ifletter=='e'orletter=='s':continueprint'Current Letter :', lettervar=10chevron_rightfilter_noneOutput:
Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : k
- Break Statement: It brings control out of the loop
forletterin'geeksforgeeks':# break the loop as soon it sees 'e'# or 's'ifletter=='e'orletter=='s':breakprint'Current Letter :', letterchevron_rightfilter_noneOutput:
Current Letter : e
- Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes.
# An empty loopforletterin'geeksforgeeks':passprint'Last Letter :', letterchevron_rightfilter_noneOutput:
Last Letter : s
- Continue Statement: It returns the control to the beginning of the loop.
We can use for in loop for user defined iterators. See this for example.
Exercise: How to print a list in reverse order (from last to first item) using while and for in loops.
This article is contributed by Ashirwad Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Output of Python Programs | Set 22 (Loops)
- Loops and Control Statements (continue, break and pass) in Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- SQL using Python | Set 1
- gcd() in Python
- Python | a += b is not always a = a + b
- zip() in Python
- max() and min() in Python
- pow() in Python
- try and except in Python
- Any & All in Python
- bin() in Python
- abs() in Python



