×

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 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.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.