Python For Loops Explained With Examples

  • Written By  

  • Published on August 5th, 2022

Table of Contents [show]
Python is a high-level, general-purpose programming language that is easy to read and run. Python is among the most broadly programming languages today. Major institutions in the world build programs and applications using this object-oriented language.

In this blog, we will discuss about the loops in Python

Loops can be a powerful tool when working with data in Python. But they can also be confusing when you’re just starting. In this blog, we’ll dive headfirst into for loops and learn how they can be used to do all kinds of compelling things when you’re doing data cleaning or data analysis in Python.

Our Learners Also Read: Top 10 Uses of Python in the Real World with Examples

While loop


The while loop is a loop that one will likely encounter when you start learning to program. It is also presumably the most intuitive to understand. As you already know, the term “loop” refers to a piece of code you repeatedly execute.

With all this in mind, one can easily understand the while loop
” when implemented
” runs a piece of code over and over again while a given condition is satisfied.

The definition above also highlights the three components you need to create a while loop in Python:

Keyword while;
” A condition that is satisfied or not.
” A block of code that you want to run repeatedly

Consider the following example:
“`
# Take user input
number = 2  

# Condition of the while loop
while number < 5 :  
    print(“Thanks”)
    # Increment the variable “number by 1.”
    number = number+1

Output:
Thanks
Thanks
Thanks“`

For LoopYou can solve a for loop in the same way as a while loop. As you’d probably expect, the “for” component in a “for” loop refers to something you do multiple times.

Keeping all of the above in mind, you can easily define a for loop as follows:

A for loop is an idea that, when implemented, executes a piece of code over and over “for” a certain number of iterations based on a sequence.

Unlike the while loop, no condition is actively involved here – you execute a part of the code repeatedly several times. In other words, while the while loop runs the block of code within it until the condition is true, the for loop only executes the code within it several times. This “number of times” is determined by the sequence or ordered list of things.
We will see more about the difference between while and for loops in a moment, but for now, focus on the following parts you need to create a for loop:

” Keyword for
” Variable
” Keyword in
” The range() function, which is a built-in function in the Python library for generating a sequence of numbers
” Code that you want to run repeatedly

For Loops in Python

“`
# Print “Thank you” 5 times
for number in range(5):
    print (“Thank you”)

Output:
Thank you
Thank you
Thank you
Thank you
Thank you
“`

While versus For Loops in Python


Let’s go back to the first while loop example to see the differences between while and for loops. You’ve already read above that the difference lies in the engaged or disengaged state, but how is that reflected in the code, and how can you switch between the two?
# Take user input
number = 2  

while number < 5 :
    print(“Thanks”)
    # Increment `number` by 1
    number = number+1

Output:
Thanks
Thanks
Thanks“`

You can utilize for loop to print the statement “Thanks” in a more controlled manner:
“`
# Print “Thanks” 3 times
for number in range(3) :  
    print(“Thank you”)

Output:
Thanks
Thanks
Thanks
“`

In a for loop, the integer specified inside the range function is the range or the number of times the control must loop and run the code in the for loop clause.

Note that the range() function count starts from 0, not 1. This means that in the above example, the count should be like 0,1,2 and not 1,2,3. This is how counting numbers in computer memory works. So when designing a for loop, remember to consider the number of ranges from 0 and not from 1.

There is another interesting difference between these two loops. A for loop is speedier than a while loop.

To understand this, let’s look at the example.
“`

import time it

# A for loop example
def for_loop():
    for number in range(10000) :  
        # Run the code 10000 times
        sum = 3+4
        #print(sum)

timeit.timeit(for_loop)
267.0804728891719
import timeit

# A while loop example
def while_loop():
    i =0
    while i<10000:
        sum = 3+4
        #print(sum)
        i+=1

timeit.timeit(while_loop)
884.9233417965908
“`

You have two loops with about 10,000 iterations in the above code block. Both look the same at first glance until you look behind the scenes and understand how the two loops work. Hint: the timeit() function will tell you what the difference might be!

Note that all Python code is compiled using the C compiler, meaning that the code you see above is split into bytecodes and then processed by the base C compiler.

When executing the for loop in the example above, the Python interpreter talks to the underlying C compiler and creates a list object of 10,000. Next, it calls an iterator that touches the index of each of the 10,000 items in the list.
On the other hand, executing a while loop does not create any list object. 

You can already imagine that iterating over an already created list object with 10,000 elements is more leisurely for the compiler than executing a boolean operation repeatedly 9999 times, the time performance of a for loop is better than a while loop. This is reflected in the execution time: the time for the for loop to complete is much less than the time it bears for the while loop to exit.

Nested Loops

A loop inside other loop is named a nested loop. The inner loop will be run once for each outer loop iteration.
Example:
“`
# Print the below statement 3 times
for number in range(3) :  
    print(“——————————————-“)
    print(“outer loop iteration “+str(number))
    # Inner loop
    for another_number in range(5):  
        print(“****************************”)
        print(“inner loop iteration “+str(another_number))

Output:
outer loop iteration 0
****************************
inner loop iteration 0
****************************
inner loop iteration 1
****************************
inner loop iteration 2
****************************
inner loop iteration 3
****************************
inner loop iteration 4
——————————————-
outer loop iteration 1
****************************
inner loop iteration 0

and so on up to outer loop 4
“`

Conclusion

In this blog, we have discussed Python for loop and its syntax in different statements.

About The Author:

logo

Digital Marketing Course

₹ 29,499/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 41,299/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot