The Wayback Machine - https://web.archive.org/web/20241122185001/https://www.geeksforgeeks.org/difference-between-for-loop-and-while-loop-in-python/
Open In App

Difference between for loop and while loop in Python

Last Updated : 24 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are ‘for loop‘ and ‘while loop‘. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print “Hello world” 100 times then we have to write a print statement 100 times which is a tedious task but with the help of loops we can do it in just a few lines of code. In this article, we will learn both types of loops separately and then their differences.

Difference between for loop and while loop in Python

For Loop Vs While Loop Banner

For loop in Python

In Python, a ‘for loop‘ is used to iterate over a sequence of items, such as a Python tuple, list, string, or range. The loop will execute a block of statements for each item in the sequence.

Python for Loop Flowchart

For loop in Python

For Loop Flow chart

Syntax of Python for loop

In the below syntax for is a keyword, var is the variable name, and iterable is an object which can be looped over or iterated over with the help of a for a loop. Objects like tuples, lists, sets, dictionaries, strings, etc. are called iterable. We can also use the range() function in place of iterable.

for var in iterable:

   # statements

Python for Loop (With Examples)

In the below example, we have created a list of items and then iterate through the list using for loop to print the items in the list.

Python3




# Create a list of items
items = ['pen', 'notebook',
         'pencil', 'lunch box']
  
# Run a loop to print
# items in a list
for item in items:
  print(item)


Output:

pen
notebook
pencil
lunch box

While Loop in Python

In Python, a while loop is used to repeatedly execute a block of statements while a condition is true. The loop will continue to run as long as the condition remains true.

Python while Loop Flowchart

While Loop in Python

While Loop Flow chart

 

Syntax of Python While loop

In the while loop condition is written just after the ‘while’ keyword and then we write the set of statements to perform some task.

while condition:

    # Set of statements

Python while Loop (With Examples)

In this example, we are using a while loop to perform the task that we have done in the example of for loop. Here, after declaring the items list we initialize the index with 0 and store the length of the items list in the variable ‘items_len’ after that running a while loop in which we have given a condition that runs the loop until the value of the index is less than items_len. Inside the while loop, we print the items of the items list using indexing and increment the value of the index by 1 to iterate over the list. 

Python3




# Create a list of items
items = ['pen', 'notebook',
         'pencil', 'lunch box']
  
# Declare a index
index = 0
  
# Store length of items list
items_len = len(items)
  
# Run a loop to print
# items in a list
while index<items_len:
  print(items[index])
  index = index+1


Output:

pen
notebook
pencil
lunch box

When no condition is given in the for and while loop?

In this case, when the condition is not given they will run into an infinite loop.

Python For Loop:

Python3




a = [1]
for i in a:
    print("GFG")
    a.append(i)


Python While Loop:

Python3




while True:
    print("GFG")


Both of the loops will run for infinite times and print GFG.

Difference between for loop and while loop in Python

Now, we will compare both loops in Python to understand where to use ‘for loop’ and where to use ‘while loop’.

For loop

While loop

For loop is used to iterate over a sequence of items.

While loop is used to repeatedly execute a block of statements while a condition is true.

For loops are designed for iterating over a sequence of items. Eg. list, tuple, etc.

While loop is used when the number of iterations is not known in advance or when we want to repeat a block of code until a certain condition is met.

For loop require a sequence to iterate over.

While the loop requires an initial condition that is tested at the beginning of the loop.

For loop is typically used for iterating over a fixed sequence of items

While loop is used for more complex control flow situations.

For loop is more efficient than a while loop when iterating over sequences, since the number of iterations is predetermined and the loop can be optimized accordingly.

While a loop may be more efficient in certain situations where the condition being tested can be evaluated quickly.



Previous Article
Next Article

Similar Reads

Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python.
3 min read
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
9 min read
Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
How to use while True in Python
In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Example: While Loop with True C/C++ Code # Python program to demonstrate # while loop with True while True: pass If we run
2 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples. Wha
6 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
How to fix "error 403 while installing package with Python PIP"?
When working with Python, pip is the go-to tool for managing packages. However, encountering a "403 Forbidden" error can be frustrating. This error typically indicates that the server refuses to fulfill the request, often due to permissions or access restrictions. In this article, we'll delve into the causes of this error and explore various soluti
4 min read
Python Do While Loops
In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is initially True and then break out of
6 min read
How to Disable Logging While Running Unit Tests in Python Django
It is never necessary to log everything while testing because it may flood the terminal with unnecessary log messages. These logs are useful during development but can be distracting when focusing on the actual test results. Disabling logging during unit tests can make our output cleaner and easier to understand. There are different ways to disable
4 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to preserve Function Metadata while using Decorators?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.Note: For more information, refer Decorators in Python How to preserve Metadata? This
2 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
7 Mistakes You Should Avoid While Building a Django Application
Django...We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications. A lot of common features
6 min read
How to not get caught while web scraping ?
In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
5 min read
Protecting sensitive information while deploying Django project
There will be a lot of sensitive information in our Django project resided in the settings.py, or local variables containing sensitive information or the POST request made using forms. So while deploying a Django project we always have to make sure they are protected especially the repositories that are publicly available. When a project is deploye
3 min read
Pyspark dataframe: Summing column while grouping over another
In this article, we will discuss how to sum a column while grouping another in Pyspark dataframe using Python. Let's create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSe
4 min read
How to Remove Index Column While Saving CSV in Pandas
In this article, we'll discuss how to avoid pandas creating an index in a saved CSV file. Pandas is a library in Python where one can work with data. While working with Pandas, you may need to save a DataFrame to a CSV file. The Pandas library includes an index column in the output CSV file by default. Further in the article, we'll understand the d
3 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
Avoid these mistakes while preparing for the CAT Exam
The CAT exam is arguably the most important exam in India for students wanting to secure the coveted MBA seats in various management institutes of the country. This is obvious from the high level of competition with more than two lakh candidates competing for seats in various MBA programs such as Finance, Marketing, Operations, etc. and only 11 can
6 min read
Sum Even and Odd Values with One For-Loop and No If-Condition Using Python
Summing even and odd numbers in a list is a common programming task. Typically, we'd use an if condition to check whether a number is even or odd. However, we can achieve this in Python efficiently using arithmetic operators and list slicing, without relying on if conditions. In this article, we'll explore how to sum even and odd values in Python u
4 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Print first m multiples of n without using any loop in Python
Given n and m, print first m multiples of a m number without using any loops in Python. Examples: Input : n = 2, m = 3 Output : 2 4 6 Input : n = 3, m = 4 Output : 3 6 9 12 We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array
3 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
Understanding for-loop in Python
A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let's begin by familiarizing o
6 min read
Do loop in Postgresql Using Psycopg2 Python
In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the conn.cursor method. The cur.execute method, passes
4 min read
Python: Map VS For Loop
Map in Python : Map is used to compute a function for different values 'in a single line of code ' . It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables . It is a way of applying same function for multiple numbers . It generates a map object at a particular location . It works
3 min read
Ways to increment Iterator from inside the For loop in Python
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let's see with the help of the below
2 min read
Python Else Loop
Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let's see the example of while loop and for loop with else below. Else with While loop Consider the below example. C/C++ Code i=0 while i<5: i+=1 print("i ="
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg