Prodotti da non perdere

In this lesson we will study the while loop in Python.

Recall, then, that a while loop is a control structure that allows you to execute a sequence of statements, as long as the specified condition is true.

So as soon as the condition becomes false, you get out of the cycle.

A cycle that never stops is called infinite. This can happen deliberately or even due to programming errors.

While Python loop syntax

The syntax of the while loop in Python is therefore this:

while condition:

    instructions # indentation is mandatory and indicates that the instructions are executed within the loop.

The colon (:) after the condition indicates the beginning of the sequence of instructions that must be executed if the condition is true.

This type of iteration is a pre-conditional construct, that is, the condition check is prior to the execution of the instructions.

Therefore, if the condition is false already at the start, the instructions will not be executed even once.

While example in Python

Let’s see a simple practical example immediately, in order to better explain the concept.

Take 10 numbers as input and add them.

To implement this program we use a counter variable, which we call for example i and we initialize it to 0. After, for each number entered, we increment it by 1 (i += 1).

So the cycle will have to continue until i equals 9 (0 to 9 are 10 numbers). Then our condition will be this: i <10.

We also initialize the sum to zero because the first time we do this: sum = sum + n, sum has no defined value. So being 0 the neutral element, I make this assignment.

Here is a simple example of program development using the while loop in Python:

i = sum = 0
while i < 10:
    n = int(input('Insert a number:'))
    sum + = n
    i += 1
print('The sum is:', sum)

The print statement is executed after the while loop as its indentation is not between the while statements.

In other programming languages ​​we use to increment the variable with i ++ but in Python this is not possible.


This is just a very simple example with the while loop in Python, in the next lesson we will deepen the subject by presenting examples of an infinite loop and a never executed loop.

Some useful links

Python tutorial

Python Compiler

Install Python


Assignment operators



How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot