Loops-in-Python
Loops-in-Python
Topperworld.in
Loop Statement
Here, we will read about these different types of loops and how to use them.
❖ Types of Loops
2 For loop This type of loop executes a code block multiple times
and abbreviates the code that manages the loop variable.
©Topperworld
Python Programming
❖ For 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 for each loop in other
languages. Let us learn how to use for in loop for sequential traversals.
• It can be used to iterate over a range and iterators.
Syntax :
s Concepts in Java
Example :
# Code to find the sum of squares of each element of the list using for loop
Output:
©Topperworld
Python Programming
Output:
Topper
World
❖ While Loop
• 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.
Syntax:
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.
©Topperworld
Python Programming
Example:
Output:
Topper World
Topper World
Topper World
• 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:
while condition:
# execute these statements
else:
# execute these statements
©Topperworld
Python Programming
Examples:
Output:
Topper World
Topper World
Topper World
In Else Block
©Topperworld
Python Programming
❖ Nested Loops
Python programming language allows to use one loop inside another
loop.
Syntax:
The syntax for a nested while loop statement in the Python programming
language is as follows:
while expression:
while expression:
statement(s)
statement(s)
Example:
# Python program to illustrate
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
©Topperworld
Python Programming
Output:
1
2 2
3 3 3
4 4 4 4
©Topperworld