Explain while loop in Python

Explain while loop in Python

The while loop in Python is a fundamental control flow statement that allows you to repeatedly execute a code block if a certain condition remains true. It’s a powerful tool for iterating over sequences, performing repetitive tasks, and controlling the flow of your program.

Understanding the while Loop Structure

The basic syntax of a while loop in Python is as follows:


# Code to be executed repeatedly

Here’s a breakdown of the key components:

  • while keyword: This keyword marks the beginning of the loop structure.
  • condition: This Boolean expression determines whether the loop should continue. The code block will be executed if the condition is evaluated to be True. If it evaluates to False, the loop will terminate.
  • Code block: This is the set of statements that will be executed repeatedly if the condition remains True.

The Boolean expression condition determines whether the loop should continue iterating. The loop body will be executed repeatedly if the condition evaluates to True. Once the condition evaluates to False, the loop terminates and runs the following code after the loop.

while loop Flow chart

while loop in Python

Simple Example of a While Loop

Consider a scenario where you want to print a greeting five times:


# Initialize a counter variable
counter = 1
# Loop until the counter reaches 6
while counter <= 5:
  print("Hello, world!")
  counter += 1

Output

Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!

Explanation

  1. We initialize a variable counter to 1.
  2. The while loop checks the condition counter <= 5. Since it is true initially, the loop body is executed.
  3. Inside the loop, the message “Hello, world!” is printed.
  4. The counter is then incremented by 1 (counter += 1).
  5. Steps 2-4 are repeated as long as the condition counter <= 5 remains true.
  6. Once the counter reaches 6, the condition becomes False, and the loop terminates.

Save $100 in the next
5:00 minutes?

Register Here

Using break and continue Statements while Loops

The while loop offers additional control flow options using the break and continue statements:

  • break statement: This abruptly exits the loop, regardless of the current condition. It can be helpful in situations where you need to terminate the loop early based on a specific event.
  • continue statement: This skips the remaining code in the current loop iteration and immediately proceeds to the next one. It’s helpful when you want to skip certain conditions within the loop without terminating it entirely.

counter = 1
while True:
  print(counter)

 # Break the loop when counter reaches 3
  if counter == 3:
    break
  counter += 1

Output

2
3

In this example, the loop runs indefinitely, as the condition True always evaluates to True. However, when the counter reaches 3, the break statement is encountered, which forces the loop to terminate immediately. The remaining iterations are skipped, and the loop exits.

On the other hand, the continue statement skips the remaining code in the current iteration of the loop and immediately proceeds to the next iteration. It allows you to control the flow within the loop without terminating it entirely.


counter = 1
while counter <= 5:
# Skip printing 5 and continue to the next iteration
  if counter == 3:
    continue
  print(counter)
  counter += 1

Output

1
2
4
5

In this example, when the counter reaches 3, the continue statement is encountered, which skips the subsequent print statement and moves to the next iteration. As a result, the number 3 is not printed. The loop continues to iterate until the counter becomes 6, at which point it terminates.

Nested Loops

Nested loops involve placing one loop inside another, allowing for more complex logic and control over code execution. The inner loop typically iterates within the scope of the outer loop, creating a nested execution flow.

Nested Loop Example

Pyramid/Triangle Creation

You can create various pyramid and triangle shapes by manipulating nested loops and varying the conditions. Here’s an example of a nested loop printing a right triangle:


rows = 5
for i in range(rows):
  for j in range(i + 1):
    print("*", end="")
  print() # Print newline after each row

Output

*
**
***
****
*****

Similarly, by adjusting the conditions and logic within the nested loops, you can create pyramids of different shapes and sizes, including:

Save $100 in the next
5:00 minutes?

Register Here

Conclusion

The while loop is a fundamental building block for Python programming. Its ability to repeatedly execute code based on a condition unlocks a vast range of possibilities. By understanding the basic structure, utilizing advanced features like break and continue, and exploring nested loops to create complex patterns like pyramids and triangles, you can unlock the full potential of the while loop in your Python code.