Python While Loop


The while loop in Python runs a block of code as long as a condition is True.


🔹 Syntax

while condition:
    # code block

The loop continues until the condition becomes False.


🔹 Simple While Loop Example

i = 1

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

🔹 Using Break in While Loop

i = 1

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

🔹 Using Continue in While Loop

i = 0

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

🔹 Else with While Loop

i = 1

while i < 4:
    print(i)
    i += 1
else:
    print("Loop finished")

🔹 Infinite Loop Example

Be careful: if the condition never becomes False, the loop will run forever.

while True:
    print("This is an infinite loop")
    break

🔹 Use Case Example

password = ""

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

print("Access granted")

🧪 Try It Yourself

Practice writing while loops with counters, conditions, and control statements like break and continue.


Practice Questions

Q1. Write a Python program to print numbers from 1 to 10 using a while loop.

Q2. Write a Python program to print even numbers from 2 to 20 using a while loop.

Q3. Write a Python program to accept numbers from the user until they enter 0.

Q4. Write a Python program to use break to stop a loop when the number is 7.

Q5. Write a Python program to use continue to skip printing number 5 in a loop from 1 to 10.

Q6. Write a Python program to count backwards from 10 to 1 using a while loop.

Q7. Write a Python program to print the multiplication table of 3 using a while loop.

Q8. Write a Python program to keep asking for a password until the correct one is entered.

Q9. Write a Python program to sum all numbers from 1 to 50 using a while loop and print the result.

Q10. Write a Python program to use else with a while loop to print a message after the loop ends normally.


Go Back Top