While Loops
1. What is a Loop?
A loop is used to repeat instructions many times in Python. Instead of writing
the same code again and again, we use loops.
2. While Loop
A while loop repeats code as long as a condition is true.
Syntax:
while condition:
instructions
Example 1: Counting from 1 to 5
i=1
while i <= 5:
print(i)
i += 1
3. Important Rule
If you forget to increase the number, the loop will run forever (infinite loop).
4. Break Statement
Used to stop the loop early.
Example:
i=1
while i <= 10:
print(i)
if i == 5:
break
i += 1
5. Continue Statement
Skips the current step of the loop.
Example:
i=0
while i < 5:
i += 1
if i == 3:
continue
print(i)
6. Practice Exercises
1. 1. Create a variable i with the value 0
2. Write a while loop that runs as long as iis less than 6
3. Inside the loop: increment i by 1
4. If i equals 3, use continue to skip that iteration
5. Print i
Solution
CodeSolution
# Create the i variable
i=0
# While loop: print 1-5, skip 3 with continue
while i < 6:
i += 1
if i == 3:
continue
print(i)