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, 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)
3. 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.
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:
- and while loop like this are similar
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:
- Note: 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.
- 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.
for iterator_var in sequence: statements(s)
It can be used to iterate over a range and iterators.
0 1 2 3
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 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
Nested Loops: Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
The syntax for a nested while loop statement in the Python programming language is as follows:
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