Description

A loop is a programming structure that repeats a sequence of instructions until a specific condition is met. A loop statement allows us to execute a statement or group of statments multiple times.

A loop is used for traversal. It is used to iterate List, String, Dictionary, Tuple. Iterating over a sequence is called traversal.

Python Programming language provides following types of loop sto handle looping requirements:

  1. For Loop
  2. While Loop
  3. Nested Loop

For Loop in Python.

The for loop is used when we want to execute the code until the given condition is true. For loop in python used to execute a block of statement or code several times until the given condition becomes false.

For loop use when we know the number of times to iterate.

  • For loop is used for sequential traversal.
  • It can be used to traverse string or array.
  • Iterating over a sequence is called traversal.
  • For loop is used to iterate over a sequence(list, string, tuple, etc)

Syntax of for loop in Python.

for variable in sequence:
    # Body of for loop
  • for is keyword.
  • variable will take the value of the item inside the sequence on each iteration.
  • Here sequence may be string, array etc.

Example of For loop in Python.

for i in range(1, 10):
    print(i)
  • range() function is used to generate sequence of numbers.
  • We can also define the start, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not provided.

for loop with string in Python.

Even strings are iterable objects, they contain a sequence of characters.

s = "String"
for i in s:
    print(i)
'''
#Output:
S
t
r
i
n
g
'''

for loop with list in python.

print each item of list.

l = ['Watch', 'Phone', 'Laptop', 'Computer', 'Bag', 'Pen', 'Headphone']
for item in l:
    print(item)

'''
#Output:
Watch
Phone
Laptop
Computer
Bag
Pen
Headphone
'''

Iterate all list item with indexing.

l = ['Watch', 'Phone', 'Laptop', 'Computer', 'Bag', 'Pen', 'Headphone']
for i in range(len(l)):
    print(l[i])

'''
#Output:
Watch
Phone
Laptop
Computer
Bag
Pen
Headphone
'''

Write a Program to print the table of any number given by user.

n = int(input("Enter the number : "))
for i in range(1, 11):
    print(f"{n} * {i} = ",n*i)

'''
#Output:

Enter the number : 5
5 * 1 =  5
5 * 2 =  10
5 * 3 =  15
5 * 4 =  20
5 * 5 =  25
5 * 6 =  30
5 * 7 =  35
5 * 8 =  40
5 * 9 =  45
5 * 10 =  50

'''

For loop with else.

  • We can also use else statement with for loop but it is not compulsory.
  • for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.
friends = ['John', 'Doy', 'Nick', 'Biden']
for item in friends:
    print(item)
else:
    print("This is else block")

'''
#Output:
John
Doy
Nick
Biden
This is else block

'''

Else part ignored if break statement terminate the loop.

friends = ['John', 'Doy', 'Nick', 'Biden']
for item in friends:
    if item == "Nick":
        break
    else:
        print(item)
else:
    print("This is else block")

'''
#Output:
John
Doy

'''

This for...else statement can be used with the break keyword to run the else block only when the break keyword was not executed. Let's take an example:

# program to display student's marks from record
student_name = input("Enter the student Name : ")
marks_of_student = {'Nick': 90, 'Denver': 55, 'Arthur': 77}

for student in marks_of_student:
    if student == student_name:
        print(marks_of_student[student])
        break
else:
    print('Data is Not Found!')

While loop in Python.

While loop statements in Python are used to repeatedly execute a certain statement as long to condition provided in the while loop statement is true.

It's body will execute until the given condition is true.

While loops let the prgram control to iterate over a block of code.

Syntax of while loop in python.

while condition:
    #body of while loop

For Example:

i = 1
while i<=10:
    print(i)
    i = i + 1

'''
#Output:
1
2
3
4
5
6
7
8
9
10

'''

while loop with list in python.

print each item of list.

l = ['Watch', 'Phone', 'Laptop', 'Computer', 'Bag', 'Pen', 'Headphone']
i = 0
while i<len(l):
    print(l[i])
    i = i + 1

'''
#Output:
Watch
Phone
Laptop
Computer
Bag
Pen
Headphone
'''

Nested loop in Python.

Loop defined within another loop is known as nested loops.

Nested Loops are the loops that are nested inside an existing loop, that is, nested loops are the body of another loop.

Syntax of nested loop in python.

for condition1:
    for condition2:
        # body of for loop

For Example:

for i in range(1, 9, 2):
    for j in range(i):
        print(i, end="")
    print()

'''
#Output:
1
333
55555
7777777

'''

Break statement in Python.

The break keyword terminates the loop and transfers the condtrol to the end of the loop. While loops, for loops can also be prematurely termicated using the break statement. The break statement exits from the loop and transfers the execution from the loop to the statement that is immediately following the loop.

i = 1
while i<20:
    if i == 11:
        break
    print(i)
    i = i + 1

'''
#Output:
1
2
3
4
5
6
7
8
9
10

'''

Continue statement in python.

It is used to skip the next statement and continue the loop.

continue statement are mostly used with loop(for, while).

The continue statement causes execution to immediately continue at the start of the loop, it skips the execution of the remaining body part of the loop. The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and the loop condition is evaluated again. If the condition is tre, then the next iteration takes place.

i = 1
while i<=10:
    if i==5:
        continue
    print(i)
    i = i + 1

'''
#Output:
1
2
3
4

'''

Differentiate between for and while loop.

Properties For While
Format Initialization, condition checking, iteration statement are written at the top of the loop Only initialization and condition checking is done at top of the loop.
Use The 'for' loop is used only when we already knew the number of iterations. The 'while' loop is used only when the number of iteration are not exactly known.
Condition If the condition is not given in 'for' loop, then loop iterates infinite times. If the condition is not given in 'while' loop, it provides compilation error.
Initialization In 'for' loop the initialization once done is never repeated. In 'while' loop if initialization is done during condition checking, then initialization is done each time the loop iterate.

 

Comments

Login is mandatory to comment Please login

Recommended Posts

Function | Docstring | Lambda | Kwargs in Python

In Python programming, a function is a block of statements that makes our code readable. If we do that function in the program, then we do not have to write the same statement of code again and again.

What is Python? How Python is interpreted? What are the tools that help to find bugs or perform static analysis? What are Python Decorators?

Python Program is a gerneral purpose of high level, intereted, interative and object-oriented scription programming language developed by Guido Van Rossum in  1991.