Experiment 5 (For Loop)
Experiment 5 (For Loop)
Loops are used in Python to execute a block of code repeatedly until a certain condition is met.
Python provides three main types of loops:
1. for loop
2. while loop
3. nested loops
1. for Loop
The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range).
Syntax:
for variable in sequence:
Examples:
apple
banana
cherry
2. while Loop
The while loop executes as long as a specified condition is True.
Syntax:
while condition:
# code block
Examples:
password = ""
while password != "1234":
password = input("Enter password: ")
print("Access granted!")
(The loop continues until the user enters "1234")
3. Nested Loops
A loop inside another loop is called a nested loop.
Syntax:
for outer in sequence:
for inner in sequence:
# code block
or
while condition1:
while condition2:
# code block
Examples:
2x1=2
2x2=4
2x3=6
3x1=3
3x2=6
3x3=9
Example 2: Nested while loop
i=1
while i <= 3:
j=1
while j <= 3:
print(f"({i},{j})", end=" ")
j += 1
print() # Move to the next line
i += 1
Output:
1. break Statement
Used to exit the loop prematurely.
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
2. continue Statement
Skips the current iteration and continues with the next iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
3. pass Statement
Output:
0
1
2
3
4
Conclusion
for loop: Best for iterating over a sequence (list, tuple, string, etc.).
while loop: Best when the number of iterations is unknown and based on a condition.
Nested loops: Used when multiple levels of iteration are needed.
Loop control statements (break, continue, pass) help manage loop execution.
The for loop is used to iterate over a sequence such as a list, tuple, string, or range.
Example: Printing numbers from 1 to 5
Explanation: The for loop iterates over the range from 1 to 5, printing each number.
1x1=1
1x2=2
1x3=3
2x1=2
2x2=4
2x3=6
3x1=3
3x2=6
3x3=9
Explanation: The outer loop iterates over i, and the inner loop iterates over j, printing the
multiplication table.