Lab 10 – Loops in Python
Objectives
• Understand why loops are needed.
• Learn for and while loops.
• Use break, continue, and pass.
• Work with the range() function.
• Write nested loops for patterns and tables.
Theory
• A loop allows us to repeat a block of code.
• Two main loops in Python:
1. for loop → used when we know how many times to repeat.
2. while loop → used when we keep repeating until a condition becomes False.
Extra:
• break → stops the loop completely.
• continue → skips the current step, moves to next.
• pass → does nothing (placeholder).
Code Examples (Step by Step)
1. For Loop
Used when we know the number of times we want to repeat.
# Print "Hello" 5 times
for i in range(5): # range(5) → 0,1,2,3,4
print("Hello", i)
2. While Loop
Runs as long as the condition is True.
# Print numbers from 1 to 5
count = 1
while count <= 5:
print("Count:", count)
count += 1 # increase by 1
3. Using range()
range(start, stop, step) generates numbers.
• start → where to begin
• stop → stop before this number
• step → difference
# Print odd numbers between 1 and 10
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
4. Looping through a List
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print("I like", fruit)
5. break and continue
# break → stop the loop
for i in range(1, 6):
if i == 3:
break
print(i) # prints 1, 2 and stops
# continue → skip one step
for i in range(1, 6):
if i == 3:
continue
print(i) # skips 3
6. pass Statement
for i in range(5):
if i == 2:
pass # does nothing
else:
print(i)
7. Nested Loops
Loop inside another loop.
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print("i =", i, "j =", j)
8. Multiplication Table
num = 5
for i in range(1, 11):
print(num, "x", i, "=", num*i)
Student Tasks
1. For Loop: Print numbers from 1 to 20.
2. While Loop: Print "Learning Python" 10 times.
3. Range: Print even numbers from 2 to 50.
4. Break: Print numbers 1–10, but stop at 7.
5. Continue: Print numbers 1–10, but skip 5.
6. Nested Loop: Print this pattern:
7. *
8. * *
9. * * *
10. * * * *
11. Multiplication Table: Ask the user for a number and print its table up to 10.
12. Reverse Counting: Print numbers from 10 down to 1 using a while loop.
13. Sum: Find the sum of numbers from 1 to 100 using a loop.
14. String Loop: Take a string input and print each character on a new line.