×

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

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python sklearn train_test_split

Sklearn: One of the most beneficial open-source libraries for learning algorithms in Python is, without a doubt, Sklearn or Scikit-Learn. The most effective tools for statistical modeling and machine learning are all included in...

6 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Make Notepad using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

5 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Io stringio Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

7 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.