In this tutorial you will learn about the Python Loops and its application with practical example.
Python Loops
In Python, Loops are a fundamental programming concept. The loop statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. This way loops are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. Loops are also known as iterating statements or looping statements. For example, if you want to print a message 100 times, then rather than typing the same code 100 times, you can use a loop.
Types of Loops In Python
In this tutorial, we will learn about the various types of loops in python. While all python loop types provide the same basic functionality, they differ in their syntax and condition checking time. In Python, we have following three types of loops –
- for loop
- while loop
- nested loop
Let’s discuss different types of loops in details :
Python for Loop
Python for loop takes a collection of data(list, tuple, string) and iterate the items one at a time in sequence.
Syntax:-
1 2 |
for <iterator_var> in <iterable_object>: #statement(s) |
Example:-
1 2 3 |
nums= range(1, 6) for n in nums: print n |
Output:-
1 2 3 4 5 |
1 2 3 4 5 |
Python while Loop
While loop will execute a block of statements as long as a test expression or test condition is true. When the expression evaluates to false, the control will move to the next line just after the end of the loop body. In a while loop, the loop variable must be initialized before the loop begins. And the loop variable should be updated inside the while loop’s body.
Syntax:-
1 2 |
while test_expression: #statement(s) |
Example:-
1 2 3 4 5 |
# prints Hello World 5 Times count = 0 while (count < 5): count = count+1 print("Hello World") |
Output:-
1 2 3 4 5 |
Hello World Hello World Hello World Hello World Hello World |
Python Nested Loops
When there is a loop statement inside another loop statement then it is known as a nested loop statement. It is possible to have a loop statement as a part of another loop statement in python programming. There can be any number of loops inside a nested loop.
Syntax:- Nested for loop
1 2 3 4 |
for <iterator_var1> in <iterable_object1>: for <iterator_var2> in <iterable_object2>: #statement(s) #statement(s) |
Syntax:- Nested while loop
1 2 3 4 |
while <exp1>: while <exp2>: #statement(s) #statement(s) |
Note:- In nesting a loop we can put any type of loop inside of any other type of loop, it is possible to have for loop inside a while loop or vice versa.