For Loop, While Loop, Nested Loops | 20 Examples with Explanation
Grade 9-12 | Computer Science | 100% Exam Ready
---
PAGE 1: WHAT IS A LOOP? - THEORY
Definition:
A loop is a programming tool that repeats a block of code multiple times without writing it again and
again.
Real Life Example:
If you need to write "I will complete my homework" 100 times, you won't write it by hand 100 times. A
loop is your robot that does it in 2 seconds.
Types of Loops in Python:
1. for loop → Used when you know "how many times" to repeat. Example: Count from 1 to 100.
2. while loop → Used when you know "until when" to repeat. Example: Keep asking for password until
correct.
---
PAGE 2-4: FOR LOOP - THEORY + CODE
Theory:
A for loop is used when the number of repetitions is fixed. It iterates over each item of a sequence like
list, string, or range() one by one.
Basic Code Structure:
, for variable in sequence:
# code to repeat
# Indentation of 4 spaces is mandatory
Example 1: Print 0 to 4
for i in range(5):
print(i)
Output:
0
1
2
3
4
Explanation: range(5) creates the sequence 0,1,2,3,4. 'i' takes each value one by one.
Example 2: Table of 2 from 1 to 10
for num in range(1, 11):
print("2 x", num, "=", 2 * num)
Output: Prints the table of 2 from 1 to 10
Example 3: Print items of a list
names = ["Ali", "Asha", "Ahmed"]
for student in names:
print("Hello", student)
Output:
Hello Ali
Hello Asha
Hello Ahmed