×

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

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

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

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

Python ascii() Function

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). This function will replace any non-ascii characters with escape characters. Syntax ascii(object) Parameter object:  An object, like String, List, Tuple, Dictionary, etc. Return This...

1 minute read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python Multiprocessing Processor

Python: 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 faster way....

4 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.

Python program to count the number of a substring in a string

Python program to count the number of a substring in a string A part of the string is called a substring. This article explains the Python program to find how many...

1 minute read.

Google Chrome API in Python

Python: 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 faster way....

3 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.