

Nevertheless, if you ever get stuck in an infinite loop in Python press ctrl + c on Windows and cmd + c on Mac to exit the loop.

In the fourth iteration, the while condition is no longer true as the value of x is now 4, therefore the while loop terminates.Ī quick note - You should be really careful while constructing a while loop because if you assign a condition which will never turn into False, the loop will run forever resulting into the infinite loop. Inside the loop first, we are printing the current value of x then incrementing the value of x by 1. In the above example we first assigned the value 1 to the variable x, then we constructed a while loop which will run until the value of x is less than or equal to 3. The condition we provide to the while statement is the controlling expression, our loop will run until the controlling statement is no longer true. In Python, a basic while loop looks like this: while : While loop favors indefinite iteration, which means we don't specify how many times the loop will run in advance. While Loop In PythonĪ while statement iterates a block of code till the controlling expression evaluates to True. This article covers the construction and usage of While loops in Python.

Loops allow programmers to set certain portions of their code to repeat through a number of loops which are referred to as iterations. Loops are an essential part of any programming language.
