Yandex

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

The loop checks the condition before executing the block. If the condition evaluates to True, the block runs. If not, the loop exits.

Example 1: Counting from 1 to 5

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

Output:

1
2
3
4
5

Explanation: 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.

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

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!

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

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

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

while True:
    num = input("Enter a positive number: ")
    if num.isdigit() and int(num) > 0:
        break
    print("Invalid input. Try again.")
    
print("Thank you! You entered:", num)

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

Explanation: 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.

Common Use Cases

  • Waiting for user input
  • Running until a certain condition changes dynamically
  • Retry mechanisms (e.g., login attempts)
  • Game loops or timers

Best Practices & Things to Watch

  • Always check that your loop condition will eventually become False.
  • Test the loop thoroughly with edge cases (e.g., zero, negative values).
  • Be cautious when modifying the condition variable inside complex loops — one oversight can create infinite loops.

Conclusion

The while loop is a versatile and foundational tool in Python. It’s perfect when the number of iterations isn’t known upfront. With proper checks and structured flow, it opens the door to dynamic, interactive, and condition-driven programs.

Practice is key — try writing your own password validators, input verifiers, or countdown timers using while loops to gain real confidence.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M