LOOPS IN
PYTHON
AGENDA
Understanding Loops
For in Loop
While Loop
Nested Loop
Examples
2
WHAT IS LOOP?
LOOPING MEANS REPEATING
SOMETHING OVER AND OVER
UNTIL A PARTICULAR
CONDITION IS SATISFIED.
FOR IN LOOP
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 foreach loop in other languages.
Syntax:
for iterator_var in sequence:
statements(s)
Example: Example:
n=4 for i in range(1, 4):
for i in range(0, n): print(i)
print(i) else:
print("No Break")
Output:
Output:
0
1 0
2 1
3 2
3
No Break
WHILE LOOP
In Python, a while loop is used to execute a block of
statements repeatedly until a given condition is satisfied.
When the condition becomes false, the line immediately
after the loop in the program is executed.
Syntax:
While expression:
Statement(s)
Example: Example:
count = 0 count = 0
while (count < 3): while (count < 3):
count = count + 1 count = count + 1
print("Hello World") print("Hello Geek")
else:
Output: print("In Else Block")
Hello World Output:
Hello World
Hello World Hello World
Hello World
Hello World
In Else Block
5
NESTED LOOPS
Python programming language allows to use one loop
inside another loop which is called nested loop.
Nested Loops Nested Loops
Syntax: Syntax:
for iterator_var in sequence: while expression:
for iterator_var in sequence: while expression:
statements(s) statement(s)
statements(s) statement(s)
Example:
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output:
1
22
333
4444
6
THANK YOU
Tahasin Mostofa Mullick