In this tutorial you will learn about the Python Loops and its application with practical example.
Python Loops
In Python, loops statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. In Python Programming Language we have following loops –
- Python for loop
- Python while loop
- Python nested loop
Python for Loop
The for loop in Python 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
The while loop will execute a block of statement as long as a test expression is true.
Syntax:-
1 2 |
while test_expression: #statement(s) |
Example:-
1 2 3 4 5 |
# prints Hello World 5 Times count = 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 loop statement inside another loop statement then it is termed as nested loop statement.
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.