LOOPS IN PYTHON
7.1 for Loop
The for loop is used to iterate over a sequence such as a list, string, or range.
Syntax:
for variable in sequence:
statement(s)
Example 1: Using range()
for i in range(1, 6):
print(i)
Example 2: Loop through a list
names = ["Ali", "Sara", "Ahmed"]
for name in names:
print(name)
7.2 while Loop
The while loop executes a block of code as long as the condition remains True.
Syntax:
while condition:
statement(s)
Example:
i = 1
while i <= 5:
1
print(i)
i += 1
Important Point: - Ensure the condition eventually becomes False to avoid an infinite loop
7.3 continue vs break
break Statement
The break statement is used to exit the loop immediately.
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
continue Statement
The continue statement skips the current iteration and moves to the next one.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
7.4 Exercise
1. Write a program to print numbers from 1 to 10 using a for loop.
2. Write a program to print even numbers from 1 to 20 using a while loop.
3. Write a program to display the sum of first 10 natural numbers.
4. Write a program that stops the loop when the number 5 is found.
5. Write a program that skips printing number 3 using continue.
6. Differentiate between for loop and while loop.