Home
Aptitude
Categories


Home » Python

Loops in Python



Loops in Python: Here, we are going to learn types of loops in details like: Condition Controlled Loops, Range Controlled Loops, Collection Controlled Loops.
Submitted by Pankaj Singh, on October 05, 2018

There are three types of loops in python:

  1. Condition Controlled Loops
  2. Range Controlled Loops
  3. Collection Controlled Loops

1) Condition Controlled Loops

In Condition controlled Loops, there is condition(expression) that controls the loop. In python there is 1 loop falls under this category.

a. while Loop

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

Output

1
2
3
4
5
6
7
8
9
10

b. Do Loop (Not Present in Python)

In Python Do While is NOT present, but we can convert while loop to work as do while loop.

a=1
while True:
    print(a)
    a=a+1
    if a>10:
        break

Output

1
2
3
4
5
6
7
8
9
10

2) Range Controlled Loops

For loop is used for implementation of Range()

There are three ways to use Range():

1. Range with 1 Parameter [range(end)] [start=0, step=1]

for i  in range(10):
    print(i,end="\t")

Output

0       1       2       3       4       5       6       7       8       9

2. Range with 2 Parameter [range(start,end)] [step=1]

for i  in range(1,10):
    print(i,end="\t")

Output

0       1       2       3       4       5       6       7       8       9

3. Range with 3 Parameter [range(start,end,step)]

for i  in range(1,10,3):
    print(i,end="\t")

Output

1       4       7



3) Collection Controlled Loops

Collection controlled loops are also implemented with the help of for loop.We need a collection object as a source. Python have various collection class like: list, tuple, set, dict.

a. with List

# with list
data = [12,45,67,23,15]
for item in data:
    print(item) 

Output

12
45
67
23
15

b. with tuple

# with tuple
data = (12,45,67,23,15)
for item in data:
    print(item) 

Output

12
45
67
23
15

c. with set

# with set
data = {12,45,67,23,15}
for item in data:
    print(item)

Output

12
45
67
23
15

d. with dict(dictionary)

# with dictionaies
data = {"item1":12,"item2":45,"item3":67,"item4":23,"item5":15}
for item in data:
    print("data["+item+"] = "+str(data[item])) 

Output

data[item3] = 67
data[item2] = 45
data[item1] = 12
data[item5] = 15
data[item4] = 23





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.