Python Loop

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

Syntax of Loop

for val in sequence:
    Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

Flowchart of Loop

Flowchart of for Loop in Python programming

 

Example: Python Loop

# Program to find
# the sum of all numbers
# stored in a list

# List of numbers
numbers = [6,5,3,8,4,2,5,4,11]

# variable to store the sum
sum = 0

# iterate over the list
for val in numbers:
    sum = sum+val

# print the sum
print("The sum is",sum)

Output

The sum is 48

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers). We can also define the start, stop and step size asrange(start,stop,step size). step size defaults to 1 if not provided. This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step sizeand generates the next number on the go. To force this function to output all the items, we can use the function list().

The following example will clarify this.

>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,8))
[2, 3, 4, 5, 6, 7]
>>> list(range(2,20,3))
[2, 5, 8, 11, 14, 17]

We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate though a sequence using indexing. Here is an example.

# Program to iterate
# through a list
# using indexing

# List of genre
genre = ['pop','rock','jazz']

# iterate over the list using index
for i in range(len(genre)):
    print("I like",genre[i])

Output

I like pop
I like rock
I like jazz

for loop with else

A 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. break statement can be used to stop a for loop. In such case, the else part is ignored. Hence, a for loop’s else part runs if no break occurs.

Here is an example to illustrate this.

# Program to show
# the control flow
# when using else block
# in a for loop

# a list of digit
list_of_digits = [0,1,2,3,4,5,6]

# take input from user
input_digit = int(input("Enter a digit: "))

# search the input digit in our list
for i in list_of_digits:
    if input_digit == i:
        print("Digit is in the list")
        break
else:
    print("Digit not found in list")

Output 1

Enter a digit: 3
Digit is in the list

Output 2

Enter a digit: 9
Digit not found in list

Here, we have a list of digits from 0 to 6. We ask the user to enter a digit and check if the digit is in our list or not. If the digit is present, for loop breaks prematurely. So, the else part does not run. But if the items in our list exhausts (digit not found in our list), the program enters the else part.

- A word from our sponsors -

spot_img

Most Popular

Leave a reply

Please enter your comment!
Please enter your name here

More from Author

Freddy Film Review

Kartik Aryan alias Freddy Ginwala is a successful dentist. When it...

Putin Plans to Replace SWIFT With Blockchain Payment System

Russian President Vladimir Putin criticized monopolies in global financial payment systems...

Bitget Crypto Exchange Flips Layoff Trend, Expands to Africa

The cryptocurrency winter has been colder for some than others. While...

New iPhone15 Leaks Reveals Stunning Design and No Sim Card

The first iPhone 15 leaks have already promised a combination of...

- A word from our sponsors -

spot_img

Read Now

Freddy Film Review

Kartik Aryan alias Freddy Ginwala is a successful dentist. When it comes to his personal life, he is not successful as since last 5 years he is desperately looking for his soulmate. One day he gets his love but that love changes his life completely. Analysis of the...

Putin Plans to Replace SWIFT With Blockchain Payment System

Russian President Vladimir Putin criticized monopolies in global financial payment systems and called for an independent and blockchain-based settlement network, speaking at the International AI Travel conference in Moscow on 24 November. Russia’s Rostec Group, a government organization, has developed a blockchain platform to launch a digital system for...

Bitget Crypto Exchange Flips Layoff Trend, Expands to Africa

The cryptocurrency winter has been colder for some than others. While some cryptocurrency exchanges are forced to conduct massive employee layoffs to weather the bear market, others like Bitget Crypto Exchange continue to make massive hires to improve their services, Bitget crypto exchange flips the layoff trend. On...

New iPhone15 Leaks Reveals Stunning Design and No Sim Card

The first iPhone 15 leaks have already promised a combination of eye-catching and controversial design changes. And excitement is only likely to grow further now a new exclusive has revealed another stunning design decision. In a move that would see Apple step back in time, a new leak from anonymous...

Get iPhone 14 Under 60000 on Flipkart – Limited Time

The original price of the iPhone 14 is Rs 79,900. However, you can get the device at a discount of Rs 5000 if you have an HDFC bank card how the deal works The original price of the iPhone 14 is Rs 79,900. However, you can get the device...

Download Unofficial TWRP for Samsung A135 Exynos

​ DISCLAIMER: I WAS NEVER, HAVE NEVER BEEN, AND WILL NEVER BE RESPONSIBLE FOR ANY DAMAGES AGAINST YOUR DEVICES. We are not responsible for bricked devices, dead SD cards, thermonuclear war, or you getting fired because the alarm app failed. Please do some research if you have any concerns about the...

Android 13 and One UI 5 for Samsung Galaxy A52

Samsung was widely panned for its slow and non-existent software support during the TouchWiz era. Over the years, though, it has made considerable improvements in this area, and with One UI 5, the Korean giant has raised the bar to a new level altogether. The Galaxy S22 was...

Presearch Coin | Earn Crypto While You Search | 25 Pre Coin for Signup

Presearch offers PRE tokens as a reward for those who search through the platform. These tokens have intrinsic value because they are the access tokens purchased by advertisers to target searchers entering certain keywords. The amount currently provided to searchers is 0.25 PRE if they search through the...

Nodle Joins First Polkadot Parachain Auction

Nodle, one of the world’s largest ecosystems of connected devices, today announced their entrance into Polkadot’s inaugural parachain slot auction and crowdloan. Nodle provides infrastructure, software, and data access to the Internet of Things (IoTs) using Bluetooth Low Energy (BLE) on existing smartphones. Polkadot is a blockchain...

How to Mine Nodle Cash IoT Network

Introduction Nodle – built on a Bluetooth Low Energy (BLE) network – is a connectivity provider for the Internet of Things (IoT). The network helps companies and cities collect data from their devices, sensors, and tags. The Nodle Network can help manufactures/operators of electronic devices collect valuable data and also help...

Ethereum Whales on Move – Relocate Over $500,000,000 Matter of Hours

A massive amount of Ethereum (ETH) worth half a billion dollars is on the move, as crypto whales relocate their ETH troves. This Friday, blockchain tracker Whale Alert spotted a series of transactions in which large Ethereum holders moved 237,419 ETH, worth $557,777,068, in just over 10 hours. In...

Dogecoin becomes the 7th accepted cryptocurrency on Coinbase

Coinbase Commerce, the e-commerce arm of the United States-based crypto exchange, has added support for Dogecoin (DOGE) payments. According to a Twitter announcement, Dogecoin became the seventh cryptocurrency for merchants to accept payments on Coinbase’s e-commerce portal. The platform currently supports Bitcoin (BTC), Bitcoin Cash (BCH), Ether (ETH),...