Skip to main content

Introduction to Python While Loops

Python While Loops

A while loop is used to repeatedly execute a block of code as long as a given condition is true.

The block of code will continue to execute as long as the condition remains true.

Once the condition becomes false, the execution of the loop stops, and the program continues with the next statement after the loop.

Here's the basic syntax of a while loop:

while condition:
# code block to be executed while the condition is true

As an examples:

count = 0

while count < 5:
print("Count:", count)
count += 1

print("Loop finished")

In this example:

  • The while loop will execute as long as the value of count is less than 5.
  • In each iteration, it will print the current value of count and then increment it by 1.
  • Once count becomes 5, the condition becomes false, and the loop finishes.
  • The program then continues with the statement after the loop, which prints "Loop finished".
danger

It's important to ensure that the condition in a while loop eventually becomes false; otherwise, the loop will continue indefinitely, resulting in an infinite loop.it may crash system

You can also use control statements like break and continue within a while loop:

The break

The break statement is used to exit the loop prematurely. When encountered, it immediately terminates the loop and transfers the control to the statement after the loop.

count = 0

while count < 5:
print("Count:", count)
if count == 3:
break
count += 1

print("Loop finished")

The continue

The continue statement is used to skip the rest of the current iteration and move to the next iteration of the loop.

count = 0

while count < 5:
count += 1
if count == 3:
continue
print("Count:", count)

print("Loop finished")

In both examples:

  • The loop will terminate when count reaches 3 due to the break statement, or it will skip printing when count is 3 due to the continue statement.

While loops are useful when you want to repeat a block of code based on a certain condition. However, it's important to ensure that the condition is properly managed to prevent infinite loops.

The else

You can also use an else block with a while loop.

The code within the else block is executed when the condition of the while loop becomes false.

The else block is optional and is executed only if the loop terminates normally (i.e., the condition becomes false).

As an example:

count = 0

while count < 5:
print("Count:", count)
count += 1
else:
print("Loop finished")

print("After the loop")

In this example:

  • The while loop continues to execute as long as count is less than 5.
  • Inside the loop, it prints the current value of count and increments it by 1. Once count becomes 5, the condition becomes false, and the loop terminates.
  • Then, the code within the else block is executed, which prints "Loop finished".
  • Finally, the program continues with the statement after the loop, which prints "After the loop".