The while
loop in Python is used to execute a block of code repeatedly, as long as a certain condition is true. The loop will continue to execute as long as the condition remains true, and will exit as soon as the condition becomes false.
Here’s the basic syntax of a while
loop:
while condition: # do something
The condition
is an expression that is checked at the start of each iteration of the loop. If the condition
is True
, then the code inside the loop is executed. If the condition
is False
, then the loop exits and the program continues with the next line of code.
Here’s an example that uses a while
loop to count from 1 to 5:
i = 1 while i <= 5: print(i) i = i + 1
In this example, we’re initializing the variable i
to 1. Then, we’re using a while
loop to print the value of i
and increment it by 1 on each iteration, until i
is greater than 5. The output of this code will be:
1 2 3 4 5
Note that if the condition
is never False
, then the loop will continue to execute indefinitely. This is known as an infinite loop, and it can cause the program to become unresponsive or crash. It’s important to make sure that the condition
will eventually become False
in order to avoid this situation. Here’s an example of an infinite loop:
i = 1 while i <= 5: print(i)
In this example, the loop will continue to execute indefinitely, because i
is never incremented, so the condition
will always be True
.