Python While Loop - Syntax and Examples

While Loop

The while loop in Python is a powerful control structure that lets you repeat a block of code as long as a specified condition remains True. It's commonly used when the number of iterations isnโ€™t predetermined โ€” making it ideal for condition-driven execution.

Basic Syntax

while condition:
    # block of code
  • while โ€“ a keyword that starts the loop.
  • condition โ€“ an expression that is evaluated before each loop iteration. If it is True, the loop continues; if False, it stops.
  • : โ€“ a colon indicates the start of the indented block.
  • The indented block of code underneath runs each time the condition is True.

Example 1: Printing from 1 to 5

The loop starts with i = 1. Each iteration prints i and increases it by 1. When i becomes 6, the condition i <= 5 fails and the loop exits.

i = 1
while i <= 5:
    print(i)
    i += 1

Output:

1
2
3
4
5

Important Check: Avoid Infinite Loops

A common pitfall with while loops is forgetting to update the condition variable, which can result in an infinite loop.

# This will run forever
i = 1
while i <= 5:
    print(i)
    # missing i += 1

Tip: Always make sure the condition variable is being modified inside the loop.

Example 2: User Input Until Correct

The loop runs until the correct password is entered. Each incorrect attempt prompts the user again.

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

print("Access granted!")

Output:

Enter the password: 123
Enter the password: pass
Enter the password: open123
Access granted!

Using break to Exit Early

You can use the break statement to exit the loop when a specific condition is met, even if the loop condition is still True.

i = 1
while True:
    print(i)
    if i == 3:
        break
    i += 1

Output:

1
2
3

Explanation: Although the loop is set to run while True, the break statement exits it when i becomes 3.

Using continue to Skip Iterations

You can use the continue statement to skip the rest of the code inside the loop for the current iteration and immediately jump to the next iteration. This is useful when you want to ignore certain values or cases without exiting the loop entirely.

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

Explanation: When i == 3, continue skips the print statement and moves to the next iteration.

Example 3: Looping Until a Valid Number is Entered

This loop validates that the input is a positive number before breaking out. Itโ€™s a real-world example of robust user input validation using a while loop.

i = 1
while i <= 5:
    print(i)
    i += 1

Output:

Enter a positive number: -1
Invalid input. Try again.
Enter a positive number: abc
Invalid input. Try again.
Enter a positive number: 5
Thank you! You entered: 5