0% found this document useful (0 votes)
9 views11 pages

Experiment 5 (For Loop)

The document provides an overview of loops in Python, detailing three main types: for loops, while loops, and nested loops. It includes syntax, examples, and explanations of loop control statements such as break, continue, and pass. Additionally, it covers advanced topics like using else with loops, iterating through dictionaries, and using enumerate().

Uploaded by

Amit kumar Dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

Experiment 5 (For Loop)

The document provides an overview of loops in Python, detailing three main types: for loops, while loops, and nested loops. It includes syntax, examples, and explanations of loop control statements such as break, continue, and pass. Additionally, it covers advanced topics like using else with loops, iterating through dictionaries, and using enumerate().

Uploaded by

Amit kumar Dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Loops in Python

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:

Example 1: Using for loop with a List

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)
Output:

apple
banana
cherry

Example 2: Using for loop with range()

for i in range(1, 6): # Loop from 1 to 5


print(i)
Output:
1
2
3
4
5

2. while Loop
The while loop executes as long as a specified condition is True.
Syntax:
while condition:
# code block
Examples:

Example 1: Simple while loop


i=1
while i <= 5:
print(i)
i += 1 # Increment i
Output:
1
2
3
4
5

Example 2: Using while loop for user input

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:

Example 1: Nested for loop (Multiplication Table)


for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"{i} x {j} = {i*j}")
print() # Blank line for readability
Output:
1x1=1
1x2=2
1x3=3

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,1) (1,2) (1,3)


(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

Loop Control Statements


Python provides special statements to control the flow of loops:

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

A placeholder that does nothing but avoids syntax errors.


for i in range(5):
if i == 3:
pass # Placeholder for future code
print(i)

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.

Different Types of Loops in Python with 10 Examples and Explanation


Python provides different types of loops to iterate through a sequence of elements or execute code
repeatedly based on a condition. The main types of loops are:
1. for loop
2. while loop
3. Nested loops
4. Loop control statements (break, continue, pass)
5. for loop with else
6. while loop with else
7. Iterating through a list using a loop
8. Iterating through a dictionary using a loop
9. Using enumerate() in a loop
10. Looping through a string

1. Simple for Loop

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

for i in range(1, 6):


print(i)
Output:
1
2
3
4
5

Explanation: The for loop iterates over the range from 1 to 5, printing each number.

2. Simple while Loop


The while loop runs as long as the condition is True.
Example: Printing numbers from 1 to 5 using while
i=1
while i <= 5:
print(i)
i += 1 # Increment i
Output:
1
2
3
4
5
Explanation: The loop runs until i becomes greater than 5.

3. Nested for Loop


A loop inside another loop.
Example: Multiplication table (1-3)

for i in range(1, 4):


for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print() # Blank line for readability
Output:

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.

4. break Statement in Loop


break is used to exit the loop prematurely.
Example: Stop the loop when i reaches 3

for i in range(1, 6):


if i == 3:
break
print(i)
Output:
1
2
Explanation: When i == 3, the loop stops due to the break statement.

5. continue Statement in Loop


continue skips the current iteration and moves to the next one.
Example: Skip number 3 in a loop

for i in range(1, 6):


if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation: When i == 3, continue skips printing 3 and continues with the next iteration.

6. for Loop with else


The else block in a for loop runs when the loop completes normally (without break).
Example: Printing numbers with else

for i in range(1, 4):


print(i)
else:
print("Loop completed successfully!")
Output:
1
2
3
Loop completed successfully!
Explanation: The else block executes after the loop finishes normally.

7. while Loop with else


Similar to for loop, while can also have an else block.
Example: while loop with else
i=1
while i <= 3:
print(i)
i += 1
else:
print("Loop ended normally!")
Output:
1
2
3
Loop ended normally!
Explanation: The else block runs after the while loop condition becomes False.
8. Iterating Through a Dictionary Using a Loop
Example: Looping through a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}

for key, value in person.items():


print(f"{key}: {value}")
Output:
name: Alice
age: 25
city: New York
Explanation: The loop iterates over dictionary key-value pairs using .items().

9. Using enumerate() in a Loop


enumerate() helps get the index and value while iterating over a list.
Example: Looping with index and value
colors = ["red", "green", "blue"]

for index, color in enumerate(colors):


print(f"Index {index}: {color}")
Output:
Index 0: red
Index 1: green
Index 2: blue
Explanation: enumerate() provides the index of each item in the list.

10. Looping Through a String


A string is an iterable, so we can loop through its characters.
Example: Iterating over a string
text = "Python"

for char in text:


print(char)
Output:
P
y
t
h
o
n
Explanation: The loop iterates over each character in the string and prints it.

You might also like