Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconPython For Loop Statement Statements: For, While, Nested Loops [Examples]

Python For Loop Statement Statements: For, While, Nested Loops [Examples]

Last updated:
15th Jun, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Python For Loop Statement Statements: For, While, Nested Loops [Examples]

Gaining expertise in python requires an understanding of every concept of the programming language. In the following article, we will be discussing one such concept of python, i.e. for loop. As it will be extensively used throughout python, understanding the concept is crucial to carry forward with other complex parts of python.  

1. For Loop in Python

In a certain program a block of statements is to be executed repeatedly for several times. Therefore loops are constructed which aids in the repeated execution of the statements. Python for loop is a type of loop statement in python that leads to the multiple executions of a sequence of statements. The iterative process is carried over a sequence like a list, tuple, or string. The indexing variable is not required to be set beforehand in for loop in python.

Syntax of a for loop in python

for x in sequence:

for statements

Where x is any value inside the sequence. The for loop keeps on executing until the last element of the sequence is reached.

An example of for loop in python

1. Input: for loop in a list

months = [“january”, “february”, “march”]

for x in months:

  if x == “february”:

    continue

  print(x, len(x))

Output: january 7

february 8

march 5

2. Input: for loop in a string

for x in “computer”:

  print(x)

Output:

c

o

m

p

u

t

e

r

3. Input: sometimes a condition of a break statement can be added before the exhaustion of the sequence.

months = [“january”, “february”, “months”]

for x in months:

if x == “february”:

break

print(x)

Output: january

4. Input: a condition of “continue” statement can be added to stop the iteration process and continue with the next.

months = [“january”, “february”, “march”]

for x in months:

  if x == “february”:

    continue

  print(x)

The range() function

For the iteration of a sequence of numbers, the range() function is used. It is a built-in function that returns a sequence of numbers. The numbers by default start from 0 and increments by 1.  A range(5) function will generate 5 values.

The values of a range() function are not stored in memory and hence, it is important to mention the start number, stop number, and also the increment. Based on these conditions, the function returns the next number.

  • For example : the below program will generate 4 values i.e. 0, 1, 2, and 3.

for x in range(4):

print(x)  

  • The start, stop and step size can also be defined sometimes along with the range() function. If no step size is provided then the default value of 1 is considered. Step is the increment that can be specified in the function.

Syntax: range(start, stop,step_size)

Example: 

Input: range(6, 12)

Output: 6, 7, 8, 9,10,11

Input: range(0, 9, 2)

Output: 0, 2, 4, 6, 8

Input: range(-10, -90, -20)

Output:  -10, -30, -50, -70,

  • The output of the range() function is usually displayed as a list but the function doesn’t actually make a list of the returned items. Therefore this saves memory.  However, if the user wants to return the output in the form of a list, the function list() is used.

Example: 

Input:   print(list(range(6)))

print(list(range(3, 9)))

print(list(range(2, 11, 2)))

Output: [0, 1, 2, 3, 4, 5]

[3, 4, 5, 6, 7, 8]

[2, 4, 6, 8, 10]

The range() function in for loop in python

For iterating through a sequence of numbers, the python for loop range() function can be used on the for loops.

An example is shown below:

Input: months = [‘january’, ‘february’, ‘march’]

for i in range(len(months)):

    print(“I like”, months[i])

Output: I like january

I like february

I like march

Our learners also read: Top Python Free Courses
upGrad’s Exclusive Data Science Webinar for you –

ODE Thought Leadership Presentation

 

2. Python For Loop With Else

The python for loop statements might be sometimes associated with additional statements of “else”. The else statements are executed when the loop is exhausted.

  • Input: for x in range(4):

print(x)

else:

print(“printing done!”)

Output: 0

1

2

3

printing done!

  • The break condition might be added to ignore the part of “else”. Breaking of a loop statement stops the execution of an else block.

Input: for x in range(5):

if x == 4: break

print(x)

else:

print(“printing done!”)

Output: 0

1

2

Top Data Science Skills to Learn

3. Python Nested Loops

Nested loops refer to the looping of statements inside a loop.

An example showing a nested loop is: 

season = [“winter”, “summer”, “autumn”]

months = [“january”, “february”, “march”]

for x in season:

 for y in months:

    print(x, y)

Output: 

winter january

winter february

winter march

summer january

summer february

summer march

autumn january

autumn february

autumn march

Read our popular Data Science Articles

Conclusion

Loops are an important segment of the python programming language as it enables the user to execute a code in a repeated manner. There might be situations when the user has to use over the same piece of code. In such cases, writing a program becomes easy and takes less time. The article portrayed the use of for loop in python script including various conditions. If you want to learn more about various python projects and topics, checkout this article.

If you are interested in gaining hands-on experience and getting trained by experts in the Python language, you can check out upGrad’s Data Science Program. The course is directed for any age group within 21-45 years of age with minimum eligibility criteria of 50% or equivalent passing marks in graduation. Any working professionals can join this Executive PG program certified from IIIT Bangalore.

With a complimentary python programming bootcamp, the course by upGrad provides 60+ industry projects along with 140+programming tools & languages. Any queries regarding the course are welcomed. 

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1Where can we use else block with a for loop in Python?

- If the loop is terminated by a break statement, the else clause will not be executed.
- If a loop does not encounter a break statement, the else clause will be executed once after all iterations have been finished.
Following are some of the use-cases of else block with a for loop –
- Instead of using flags, we can use break with else to search.
- It can be used to check for limits or boundaries.
- If you want to execute something based on the fact whether the inner loop was executed successfully or has hit a break statement, you can use the else block.
- If you want to break the flow on exceptions, you can use them.

2 How to use for loops using range() in Python?<br />

Range is one of Python's built-in immutable sequence types. Range() is used in loops to control how many times the loop is repeated. When using range(), you can give it between one and three integer arguments:
start is the integer value at which the series begins; if this is omitted, the sequence starts at 0.
stop is always required and specifies the number that is tallied up to but not included in the sequence.
If step is omitted, the next iteration's increase (or reduction in the case of negative numbers) is set to 1.
We'll look at an example of different arguments that can be passed to range().
for i in range(0,15,3):
print(i)
Here, the loop starts from 0 and ends at 14 at a step of 3. So, the output is – 0, 3, 6, 9, 12.

3 Should I choose a while or a for loop in my Python program?

- Before the loop's assertions, a condition must be given in most while condition loops. The statements in the loop's body may never be performed as a result of this. Furthermore, for while loops, it is not always clear how many times the loop will execute. Instead, for loops, concentrate on the iterator, which determines how often the instructions in the loop's body are executed.
- If you know exactly how many elements you want to traverse over, a for loop is preferable. A while loop, on the other hand, is better for evaluating a boolean statement rather than a list of elements to loop over.

Explore Free Courses

Suggested Blogs

Most Common PySpark Interview Questions &#038; Answers [For Freshers &#038; Experienced]
20603
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5036
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5113
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5056
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17381
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types &#038; Techniques
10661
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
79965
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories &#038; Types [With Examples]
138284
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
68404
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon