πŸ” Python While Loop β€” Repeat Actions Until a Condition Changes

Introduction 🌟

A while loop repeatedly executes a block of code as long as its condition remains True. It is ideal for situations where you don't know in advance how many times the loop should run.

Note

πŸ’‘ Use a while loop when the number of iterations depends on a condition, not a fixed count.

1. Basic While Loop Structure 🧱

basic_while.py

i = 1

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

βœ”οΈ The loop starts at i = 1
βœ”οΈ Runs until i <= 5 becomes False
βœ”οΈ Each iteration increases i by 1

2. Infinite Loop ⚠️

A while loop becomes infinite if its condition never becomes False.

infinite_loop.py

while True:
    print("This will run forever!")

Note

⚠️ Avoid infinite loops unless intentionally used (like servers, listeners, etc.).

3. Using While Loop With User Input ⌨️

while_input.py

password = ""

while password != "admin":
    password = input("Enter password: ")

print("Access granted!")

4. While Loop With Break πŸ›‘

break stops the loop immediately, even if the condition is still True.

while_break.py

i = 1

while i <= 10:
    if i == 5:
        break
    print(i)
    i += 1

Note

βœ”οΈ Loop stops when i becomes 5.

5. While Loop With Continue πŸ”„

continue skips the current iteration and moves to the next one.

while_continue.py

i = 0

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

Note

βœ”οΈ Skips printing the value 3.

6. While Loop With Else Block 🎯

The else block runs when the loop condition becomes False normally (no break).

while_else.py

i = 1

while i <= 3:
    print(i)
    i += 1
else:
    print("Loop completed")

7. Nested While Loops πŸͺœ

nested_while.py

i = 1

while i <= 3:
    j = 1
    while j <= 3:
        print(i, j)
        j += 1
    i += 1

8. Using While Loop for Menus πŸ“‹

menu_example.py

choice = 0

while choice != 3:
    print("1. Say Hello")
    print("2. Say Bye")
    print("3. Exit")
    choice = int(input("Enter option: "))

    if choice == 1:
        print("Hello!")
    elif choice == 2:
        print("Bye!")
    elif choice == 3:
        print("Exiting...")
    else:
        print("Invalid choice")

9. Common Mistakes ⚠️

  • Forgetting to update the loop variable (infinite loop).
  • Using incorrect conditions.
  • Misplacing break or continue.

10. Real-World Example 🌍

real_world_example.py

attempts = 0

while attempts < 3:
    pin = input("Enter PIN: ")
    if pin == "1234":
        print("Login successful!")
        break
    else:
        print("Wrong PIN")
        attempts += 1
else:
    print("Account locked!")

Conclusion πŸŽ‰

>>β€œWhile loops give your program the power to repeat until the job is done.” πŸ”

You now understand Python’s while loop thoroughly! Want the next topic? Try For Loop, Range(), Loop Control Statements, or Nested Loops. Just tell me! 😊