1.
while Loop in Python
A while loop runs as long as a condition is True.
Syntax:
while condition:
# code to run
Example 1: Print numbers 1 to 5
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Explanation:
• Start from i = 1
• Check condition i <= 5
• Run loop
• Increase i each time
• Stop when condition becomes False
Important:
If you forget to update the variable → infinite loop
i=1
while i <= 5:
print(i) # This will run forever
Example 1: Print numbers 1 to 10
i=1
while i <= 10:
print(i)
i += 1
Explanation:
• Start with i = 1
• Loop runs until i <= 10
• After every print, i increases by 1
• Stops when i = 11
Example 2: Print even numbers from 2 to 10
i=2
while i <= 10:
print(i)
i += 2
Explanation:
• Start from 2
• Increase by 2 each time → 2, 4, 6, 8, 10
• Only even numbers are printed
Example 3: Sum of first 5 numbers
i=1
total = 0
while i <= 5:
total += i
i += 1
print("Sum =", total)
Explanation:
• Add numbers one by one: 1+2+3+4+5
• Store result in total
• Final output = 15
Example 4: Reverse counting (10 to 1)
i = 10
while i >= 1:
print(i)
i -= 1
Explanation:
• Start from 10
• Decrease by 1 each time
• Stops when it reaches 0
Example 5: User input until correct number
num = 0
while num != 5:
num = int(input("Enter number (5 to stop): "))
Explanation:
• Loop keeps running until user enters 5
• Condition becomes false only when input = 5
• Good for validation or repeated input
WHILE LOOP PRACTICE (Beginner Level)
Question 1
Print numbers from 1 to 20
Question 2
Print numbers from 10 to 1 (reverse order)
Question 3
Print all odd numbers from 1 to 15
Question 4
Print multiplication table of 5
Output:
5x1=5
5 x 2 = 10
...
Question 5
Find the sum of numbers from 1 to 10
Question 6
Count how many numbers are between 1 to 50
(Just count, don’t print all)
Question 7
Take input from user until they enter 0
Print each number they enter
Question 8
Print numbers from 1 to 30 but:
• Skip multiples of 3
Question 9
Find the factorial of a number
Example:
5 → 5 × 4 × 3 × 2 × 1 = 120
Question 10
Keep asking user for password until they enter "python123"
Then print: "Login Successful"
Bonus Challenge (Little tricky)
Question 11
Print this pattern using while loop:
*
**
***
****
*****