While loops

A while loop is used to repeatedly execute a block of code as long as a certain condition is true. It allows us to create a loop that keeps running until a specific condition is met.

Here's the basic structure of a while loop:

while condition:
    # code to be executed

The condition is an expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. After each iteration, the condition is checked again, and the loop continues until the condition becomes false.

Let's see an example to understand it better:

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

In this code, we initialize a variable count to 0. The while loop runs as long as count is less than 5. Inside the loop, we print the current value of count and then increment it by 1 using the += operator. This process continues until count becomes 5, at which point the condition becomes false and the loop stops.

The output of this code will be:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

As you can see, the loop executed five times because the condition count < 5 was true for the first five values of count.

It's important to be careful when using while loops to avoid creating infinite loops. An infinite loop is a loop that never stops because the condition always remains true. For example:

# This is an infinite loop!
while True:
    print("This is an infinite loop!")

In this code, the condition True is always true, so the loop will continue indefinitely. To stop an infinite loop, you can press Ctrl + C in the terminal or stop the execution of the program.

While loops are useful when you want to repeat a block of code until a specific condition is met. They give you control over the flow of your program and allow us to create more dynamic and interactive applications.