[Python] While Loop

[Python] While Loop

Python While Loop: A Complete Guide

In Python, a while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The syntax for the while loop is as follows:

while condition:
    # Code to be executed as long as the condition is True

Here’s an explanation and sample code for the while loop in Python:

Example 1:

count = 0

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

Output:

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

In this example, the condition count < 5 is checked before each iteration of the loop. As long as the condition is True, the code inside the while loop block is executed. In each iteration, the value of count is printed, and then count is incremented by 1. The loop continues until the condition becomes False.

Example 2:

num = 10

while num > 0:
    print(num)
    num -= 2

Output:

10
8
6
4
2

In this example, the while loop continues until the condition num > 0 becomes False. Inside the loop, the value of num is printed, and then num is decremented by 2 in each iteration.

Example 3:

password = ""

while password != "secret":
    password = input("Enter the password: ")

print("Access granted!")

Output:

Enter the password: hello
Enter the password: 12345
Enter the password: secret
Access granted!

In this example, the while loop is used to prompt the user to enter a password. The loop continues until the entered password matches the string “secret”. Once the condition becomes False, the loop terminates, and “Access granted!” is printed.

It’s important to ensure that the condition within a while loop will eventually become False; otherwise, the loop will run indefinitely, resulting in an infinite loop.

The while loop provides a way to repeatedly execute a block of code as long as a condition is true. It’s useful when you need to iterate based on a condition that may change during runtime.

Leave a Comment