-
Hajipur, Bihar, 844101
The while
loop in Python runs a block of code as long as a condition is True
.
while condition:
# code block
The loop continues until the condition becomes False
.
i = 1
while i <= 5:
print(i)
i += 1
i = 1
while i < 10:
print(i)
if i == 5:
break
i += 1
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
i = 1
while i < 4:
print(i)
i += 1
else:
print("Loop finished")
Be careful: if the condition never becomes False
, the loop will run forever.
while True:
print("This is an infinite loop")
break
password = ""
while password != "admin":
password = input("Enter password: ")
print("Access granted")
Practice writing while loops with counters, conditions, and control statements like break
and continue
.
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.
Q1: What is a while loop used for?
Q2: What will happen if the condition is always True?
Q3: What keyword is used to exit a loop?
Q4: What keyword is used to skip one iteration?
Q5: Can you use else with while loop?
Q6: What happens if the condition is False at the beginning?
Q7: What is the output of this loop: i = 0; while i < 3: print(i); i += 1?
Q8: When is the else part of a while loop executed?
Q9: Which loop is better for repeating until user input is correct?
Q10: What is required in a while loop to avoid infinite loop?