Python While Loop :–
What is a while loop?
A while loop in Python repeatedly executes a block of code as long as a specified condition
is True.
Syntax:
while condition:
# code block to execute
• The loop continues until the condition becomes False.
• You must ensure the condition changes within the loop, otherwise it will cause an
infinite loop.
Example 1: Counting from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Infinite Loop Example
while True:
print("This will run forever!")
Use Ctrl+C to stop an infinite loop during execution.
Break Statement
The break statement exits the loop prematurely.
x = 1
while x < 10:
if x == 5:
break
print(x)
x += 1
Output:
1
2
3
4
Continue Statement
The continue statement skips the rest of the code in the loop for that iteration.
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
Output:
1
2
4
5
Use Cases of while Loops
• Repeating tasks when you don’t know how many times to repeat in advance.
• Waiting for user input.
• Games, simulations, menus, etc.
Tips
• Always check your loop condition.
• Make sure there is an exit condition, or use break.
️ Practice Questions:-
1⃣ Print numbers from 10 to 1 using a while loop.
i = 10
while i >= 1:
print(i)
i -= 1
2⃣ Keep asking the user for a number until they enter 0.
while num != 0:
num = int(input("Enter a number (0 to stop): "))
3⃣ Find the sum of first n natural numbers (where n is input from
n = int(input("Enter n: "))
sum_ = 0
i = 1
while i <= n:
sum_ += i
i += 1
print("Sum:", sum_)
4⃣ Print only even numbers from 1 to 20 using while.
i = 1
while i <= 20:
if i % 2 == 0:
print(i)
i += 1
5⃣ Create a simple password checker that loops until the user
types the correct password.
correct_password = "Abhishek"
password = input("Enter password: ")
while password != correct_password:
password = input("Incorrect. Try again: ")
print("Access granted")
tracked files-
git add .