×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Loops in Python

By IncludeHelp Last updated : December 08, 2024

There are three types of loops in python:

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

1) Python 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.

Python while Loop

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

Output

1
2
3
4
5
6
7
8
9
10

Python 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) Python Range Controlled Loops

For loop is used for implementation of range() method.

There are three ways to use Range():

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

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

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

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

Output

1       4       7

3) Python 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, and dictionary.

Python Collection Controlled Loops With List

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

Output

12
45
67
23
15

Python Collection Controlled Loops With Tuple

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

Output

12
45
67
23
15

Python Collection Controlled Loops With Set

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

Output

12
45
67
23
15

Python Collection Controlled Loops 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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.