While Loop in Python

A while loop is another important concept in Python that helps you in executing a block of code multiple times until a certain condition is met. Imagine you are watching your favorite show, and you continue watching episodes as long as your internet connection is stable. The moment your internet disconnects, you stop watching. Similarly, a while loop runs repeatedly as long as a condition remains True and stops when the condition becomes False.

In this blog post, I will introduce you to the while loops in Python, their syntax, working, and practical examples.

While Loop
While Loop

What is a While Loop?

A while loop is used when the number of iterations is not known in advance but depends on a condition. A while loop keeps going as long as a certain condition is true, instead of going through a specific list of items like a for loop.

Syntax:

while condition:
    # Code block to execute
Python
While Loop
While Loop

How Does While Loop Work?

  • The loop starts with the while keyword, followed by a condition that evaluates to True or False.
  • The condition is an expression that check the condition of the loop before running the code. If the condition is True, the code block is executed. If the condition is False, the code block is skipped.
  • After executing the code inside the loop, the program goes back to check the condition again.
    If it still remains True, the code block is executed once more, and this process repeats until the condition becomes False.

For example:

count = 0  # Initialize a variable

while count < 5:  # Condition to check
    print(count)  # Code block to execute
    count += 1    # Update the variable

# Output: 0
#         1
#         2
#         3
#         4
Python
  • Before using a while loop, we usually initialize a variable that we will use in the condition. In this case count = 0.
  • Then The loop checks the condition if count < 5. Since 0 < 5 is True, it enters the loop.
  • And execute the indented code block inside the loop and print the value of count which is 0. Then increases count by 1, so now the count is 1.
  • Then the loop goes back to check the condition again. Now it checks if 1 < 5, which is still True, so it prints 1 and increases count to 2. This process continues until count reaches 5.
  • And when count is 5, the condition 5 < 5 become False, so the loop stops. and the immediately after the loop will executed.

Example 2:

correct_password = "python123"
user_input = ""

while user_input != correct_password:
    user_input = input("Enter password: ")
    
print("Access Granted!")
Python

This loop will keep asking for the password until the user enters "python123".

The Infinite Loop Problem

What will happen if you don’t update the variable value? If you forget to change the condition inside the while loop, you might create an infinite loop that never stops running! This happen because the condition is always True and it never becomes False.

number = 1

while number <= 5:
    print(number)  # Forgot to update the number!
Python

To avoid infinite loops:

  • Make sure that the loop condition will always evaluate to false.
  • Always update the variables within the loop that control the loop condition.
  • You can use break statement if necessary. (We will learn about it later)
  • If you are not sure whether a loop will terminate, you can set a maximum number of iterations.
  • If you stuck in infinite loop, you can use Ctrl + C to stop and exit form the program.

Conclusion

In this blog, we explored the while loop, its syntax, and how it works in Python. We covered practical examples and discussed common mistakes like infinite loops. While loops are very useful for situations where you don’t know how many times the loop should run.

Next, you will learn about nested loops and jump statements, which further enhance the control flow in Python programs.

While Loop in Python

Check the loop condition

1 / 4

In the example while count < 5: print(count), what happens after the count reaches 5?

To break the loop

2 / 4

How can you stop an infinite loop?

Forgetting to update a variable

3 / 4

Which of the following will cause an infinite loop?

Based on a condition being True

4 / 4

What is the purpose of a while loop in Python?

Your score is

The average score is 0%

0%

Leave a Reply

Your email address will not be published. Required fields are marked *