[go: up one dir, main page]

0% found this document useful (0 votes)
149 views9 pages

? Chapter 7 - Loops in Python

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

📚 Chapter 7: Loops in Python

🔄 Introduction to Loops:
Loops are fundamental in programming, enabling us to execute a block of code repeatedly
without having to write the same code multiple times. This reduces redundancy and allows for
more efficient code management.

In Python, there are three types of loops:

1. For Loop
2. While Loop
3. Do-While Loop (Not a built-in loop, but achievable using a while loop)

1️⃣ For Loop:

A for loop is used to iterate over a sequence, which could be a list, tuple, string, or other
iterable objects. The loop variable takes on the value of each element in the sequence on every
iteration, making it particularly useful when you know the exact number of iterations required.

Syntax:

for variable in sequence:


# Code to execute

Example 1: Iterating Over a Range of Numbers

for i in range(1, 6):


print(i) # Outputs: 1 2 3 4 5

Example 2: Iterating Over a List

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


for fruit in fruits:
print(fruit)
# Outputs: apple banana cherry
Example 3: Iterating Over a String

for char in "Python":


print(char)
# Outputs: P y t h o n

🔄 Nested For Loop:


A nested for loop is when a for loop exists inside another for loop. This allows you to perform
more complex iterations, such as iterating through a matrix (2D array).

Example:

for i in range(1, 4):


for j in range(1, 4):
print(i, j)
# Outputs:
# 1 1
# 1 2
# 1 3
# 2 1
# 2 2
# 2 3
# 3 1
# 3 2
# 3 3

2️⃣ While Loop:

A while loop runs as long as a given condition is true. Unlike a for loop, the number of iterations
in a while loop isn’t fixed beforehand. This makes it particularly useful when the condition is
dependent on dynamic factors.

Syntax:
python
Copy code
while condition:
# Code to execute

Example 1: Basic While Loop


python
Copy code
i = 1
while i <= 5:
print(i) # Outputs: 1 2 3 4 5
i += 1

Example 2: Infinite While Loop

An infinite loop continues until it’s forcibly stopped. Be cautious with such loops, as they can
cause your program to hang.

python
Copy code
while True:
print("This is an infinite loop")
break # Adding a break statement to exit the loop

🔄 Nested While Loop:


Just like for loops, you can nest while loops within each other.

Example:

i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
# Outputs:
# 1 1
# 1 2
# 1 3
# 2 1
# 2 2
# 2 3
# 3 1
# 3 2
# 3 3

3️⃣ Do-While Loop (Emulation in Python):

Python does not have a built-in do-while loop like some other programming languages (e.g.,
C++ or Java). However, you can simulate the behavior of a do-while loop using a while loop.
The main idea is to ensure that the code block is executed at least once before checking the
condition.

Concept:

while True:
# Code block (executed at least once)
if not condition:
break

Example:

i = 1
while True:
print(i)
i += 1
if i > 5:
break
# Outputs: 1 2 3 4 5

🔢 The Range Function:


The range() function generates a sequence of numbers, which is useful for creating loops. By
default, it starts from 0, increments by 1, and stops before a specified number.

Syntax:
range(start, stop, step)

● start: The starting value (inclusive, default is 0)


● stop: The stopping value (exclusive)
● step: The increment value (default is 1)

Example 1: Basic Usage

for i in range(5):
print(i) # Outputs: 0 1 2 3 4

Example 2: Specifying Start and Stop

for i in range(2, 7):


print(i) # Outputs: 2 3 4 5 6

Example 3: Specifying Step

for i in range(1, 10, 2):


print(i) # Outputs: 1 3 5 7 9

🟢 For Loop with Else:


In Python, you can use the else clause with a for loop. The code inside the else block runs after
the loop finishes, unless the loop is terminated by a break statement.

Syntax:

for i in range(5):
# Loop code
else:
# Code to execute after the loop

Example:
for i in range(5):
print(i)
else:
print("Loop is finished")
# Outputs:
# 0 1 2 3 4
# Loop is finished

🛑 Break Statement:
The break statement terminates the loop prematurely. It’s often used when you need to exit the
loop after meeting a certain condition.

Syntax:

for i in range(5):
if i == 3:
break
print(i)

Example:
for i in range(5):
if i == 3:
break # Exits the loop when i == 3
print(i) # Outputs: 0 1 2

⏭ Continue Statement:
The continue statement skips the current iteration and proceeds with the next one. It’s useful
when you want to bypass specific conditions within a loop.

Syntax:

for i in range(5):
if i == 3:
continue
print(i)

Example:
for i in range(5):
if i == 3:
continue # Skips the iteration when i == 3
print(i) # Outputs: 0 1 2 4

🚫 Pass Statement:
The pass statement is a placeholder that does nothing. It’s commonly used when a statement is
syntactically required but you don’t want to execute any code.

Syntax:

for i in range(5):
pass

Example:

for i in range(5):
if i == 3:
pass # Does nothing here
print(i) # Outputs: 0 1 2 3 4

✨ Advanced Loop Techniques:


1. Looping Through a Dictionary:

You can iterate through the keys and values of a dictionary using a loop.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}


for key, value in my_dict.items():
print(key, value)
# Outputs:
# a 1
# b 2
# c 3

2. Using the Enumerate Function:

The enumerate() function adds a counter to an iterable, making it useful when you need both
the index and the value.

Example:

names = ["Alice", "Bob", "Charlie"]


for index, name in enumerate(names):
print(index, name)
# Outputs:
# 0 Alice
# 1 Bob
# 2 Charlie

3. List Comprehensions:

List comprehensions provide a concise way to create lists using loops in a single line of code.

Example:

squares = [x**2 for x in range(5)]


print(squares) # Outputs: [0, 1, 4, 9, 16]

📝 Summary:
● For Loop: Ideal for iterating over sequences or a range of numbers.
● While Loop: Continues as long as a specified condition is true.
● Break Statement: Exits the loop prematurely.
● Continue Statement: Skips the current iteration.
● Pass Statement: A placeholder that does nothing.
Loops are a powerful tool in Python, enabling you to write clean, efficient code by eliminating the
need for repetitive tasks. Whether you're iterating through data, controlling flow with break and
continue, or simply learning the fundamentals, mastering loops is essential for any Python
developer! 🚀

You might also like