Loops in Python
Python programming language provides the 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
In python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed.
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 of Python While Loop
Let’s see a simple example of while loop in Python.
Hello Geek Hello Geek Hello Geek
Using else statement with While Loop in Python
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.
Syntax of While Loop with else statement:
while condition: # execute these statements else: # execute these statements
Examples of While Loop with else statement
Here is an example of while loop with else statement in Python:
Hello Geek Hello Geek Hello Geek In Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of time, we can use the while loop in Python to do so.
Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, 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.
for iterator_var in sequence: statements(s)
It can be used to iterate over a range and iterators.
0 1 2 3
Example with List, Tuple, string, and dictionary iteration using For Loops in Python
We can use for loop to iterate lists, tuples, strings and dictionaries in Python.
List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345 Set Iteration 1 2 3 4 5 6
Iterating by the 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:
geeks for geeks
Using else statement with for loop in Python
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.
geeks for geeks Inside Else Block
Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
for iterator_var in sequence: for iterator_var in sequence: statements(s) statements(s)
The syntax for a nested while loop statement in the 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.
1 2 2 3 3 3 4 4 4 4
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.
the continue statement in Python returns the control to the beginning of the loop.
Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : k
The break statement in Python brings control out of the loop.
Current Letter : e
We use pass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.
Last Letter : s
How for loop in Python works internally?
Before proceeding to this section, you should have a prior understanding of Python Iterators.
Firstly, lets see how a simple for loop looks like.
apple orange kiwi
Here we can see the for loops iterates over iterable object fruit which is a list. Lists, sets, dictionaries are few iterable objects while an integer object is not an iterable object. For loops can iterate over any of these iterable objects.
Now with the help of the above example, let’s dive deep and see what happens internally here.
- Make the list (iterable) an iterable object with help of the iter() function.
- Run an infinite while loop and break only if the StopIteration is raised.
- In the try block, we fetch the next element of fruits with the next() function.
- After fetching the element we did the operation to be performed with the element. (i.e print(fruit))
apple orange kiwi
We can see that under the hood we are calling iter() and next() method.
Please Login to comment...