Loops in python || Types of loops in python || For Loop in python example

Loops in python

Loops in python

In Python, there are two types of Loops

  1. For Loop 
  2. While Loop

1. For Loop

The For Loops are used to traverse an array, list, or string. Hence it is used for sequential traversing. For Loop is used in Python is different from For Loop used in C language.
Example 1:-
#program for loops in python

n=5
for i in range(n):
    print(‘This is For Loop’)

Output

This is For Loop
This is For Loop
This is For Loop
This is For Loop
This is For Loop

Example 2:-
#program for loops in python

n=7
for i in range(n):
    print(i)

Output

0
1
2
3
4
5
6

Example 3:-

for i in range(2,n):
    print(i)

Output

2
3
4
5
6

iterating over the List in python

print(“List Iteration”)
list = [ “Python”, “Java”, “C”, “PHP”]
for i in list:
    print( i )

Output

Python
Java
C
PHP

iterating over the String in python

print(” String Iteration “)
s=”Python”
for i in s:
    print( i )

Output

P
y
t
h
o
n

iterating over the Tuple in python

print(” Tuple Iteration “)
t=(“MySQL”, “Oracle”, “MongoDB”)
for i in t:
    print( i )

Output

MySQL
Oracle
MongoDB

2. While Loop

While Loop is used to execute a block of statements repeatedly until a given condition is true. And when the condition is false program is executed immediately after the Loop.
Example :-

n=0
while(n<4):
    print(‘Hello Wolrd’)
    n=n+1

Output

Hello World
Hello World
Hello World
Hello World

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *