Sitemap
Bollavaram Harshavardhan Reddy

Bollavaram Harshavardhan Reddy

Software Engineer - 3+ years experienced

Python — Loops

2 min readOct 18, 2024

Loops help to execute a block of code repeatedly

A loop is a control structure that repeats a block of code a set number of times or until a certain condition is met.

Loops are essential for reducing code redundancy and simplifying tasks that require repetitive actions.

Python offers two primary looping constructs:

‘for’ loop:

The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range).

It enables you to execute a block of code for each item in the sequence.

One of Python’s strengths is its simplified for loop, which eliminates the need to manually manage loop counters (as in languages like C or Java).

#Syntax
for item in sequence:
fruits = ['Apple','Banana','Grapes','Orange']

for fruit in fruits:
print(fruit)

In the above we have a fruits list , using for loop we can iterate over the items in list.

Get Bollavaram Harshavardhan Reddy’s stories in your inbox

Join Medium for free to get updates from this writer.

iterating with ‘range’

The range() function is often used in combination with for loops to generate a sequence of numbers. It can take up to three arguments: start, stop, and step.

for i in range(5):
print(i)

In this example for loop displays the numbers from 0 to 4.

when using range we can increment or decrement the numbers using step.

for i in range(0,10,2):
print(i)

In this example the for loop displays 0,2,4,6,8

‘while’ loops

Another looping statement in python is while loop

#syntax
while condtion:
#while loop
count=0
while count<=10:
print(count)
count+=1

In this example we create while loop which will check for the count.

The initial count is ‘0’, everytime when the loop executes it increments the count by 1, Once the count reaches 10 it terminates.

--

--

Bollavaram Harshavardhan Reddy
Bollavaram Harshavardhan Reddy

Written by Bollavaram Harshavardhan Reddy

Software Engineer - 3+ years experienced