×

Difference between For Loop and While Loop in Python

What is the “For” loop?

The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is a compact way of writing a repetitive process, allowing us to perform a set of actions multiple times on a given data structure.

The For loop's basic syntax consists of three parts:

  1. Initialization: The starting value of the loop is set.
  2. Condition: If this is true, the loop will continue to execute.
  3. Increment/Decrement: The value of the loop variable is updated each time the loop iterates.

For loops can iterate over arrays, lists, and other data collections. In each iteration of the loop, the current value of the loop variable is used as the index for accessing the elements of the collection. This makes for loops an efficient way to perform operations on each element in a collection.

Suppose we want to print the numbers 2-13. In Python, we would write it like this:

Example:

#for loop program
for i in range(2, 13):
    print(i)

Output:  

2
3
4
5
6
7
8
9
10
11
12

The value of “I” will be printed in each iteration of this loop's 11 iterations. The range() function returns a number sequence from the start value to the end value.

What is the “While” loop?

In the “While” loop, if the provided condition is true, a block of code is continually executed. In Python, the general syntax for a while loop is:

while condition:
    code block

The code block will be executed until the condition is satisfied. If the condition is initially false, the code block will be skipped.

Example:

count = 1
while count <= 5:
    print(count)
    count += 1

Output:

1
2
3
4
5

This code will print the numbers 1 to 5, as the condition count <= 5 is true, and the count is incremented by 1 in each iteration of the loop. It is important to make sure that the condition will eventually become false, otherwise, the loop will continue indefinitely, creating an infinite loop.

A while loop is a useful tool when you need to perform a task repeatedly while a certain condition is met. You can use the while loop to control the flow of the program and make decisions based on conditions.

In a while loop, the condition is evaluated before each iteration, so if the condition becomes false, the loop will stop and the control will be transferred to the next line after the loop. It's possible to use multiple conditions in the while loop, just like in the “if” statement, by using logical operators such as “and, or, and not”.

In some cases, you might need to break out of the loop early, before the condition becomes false. This is possible with the break statement.

Example:

count = 1
while count <= 10:
    if count == 5:
        break
    print(count)
    count += 1

Output:

1
2
3
4

Difference Between For Loop and While Loop

  • A for loop is used for iterating over a range or sequence of items and executing a block of code for each item. On the other hand, a while loop is used to execute a block of code repeatedly as long as a specified condition is true. The key difference is that for loop is designed to run a predetermined number of times, while the while loop will continue to run as long as the condition is met.
  • When you need to repeat a specific block of code a certain number of times, for loops come in scene. They are also useful when working with lists, arrays, or other data structures where the number of iterations is known ahead of time. The syntax of a for loop typically includes an initialization statement, a condition that is evaluated before each iteration, and an increment or decrement statement that is executed after each iteration.
  • The use of while loops, on the other hand, is ideal when it is impossible to predict how many iterations would be required. Typically, they are employed to repeatedly run a piece of code until a particular condition is satisfied. A while loop's syntax includes a condition that is tested before each iteration, and the loop will keep running as long as the condition is still true.

Related Topics

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Python Generator

Python Generator: A Function is said to be a Python Generator that produces or generates a sequence of results. A Python Generator maintains its native state to work so that...

6 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.