Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
Loops allow you to repeat a block of code multiple times, enabling you to perform repetitive tasks.
for loops are used when you have a predefined sequence (e.g., a list, tuple, string
, or range
) over which you want to iterate.
Syntax:
for item in iterable:
# Code to execute for each item in the iterable
Example:
pythonfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This code uses a for loop to iterate through a list of fruits and print each one.
while loops continue executing as long as a specified condition is True.
Syntax:
pythonwhile condition:
# Code to execute as long as the condition is True
Example:
pythoncount = 0
while count < 5:
print(count)
count += 1
This code uses a
loop to print numbers from 0 to 4.while
The break statement is used to exit a loop prematurely when a certain condition is met.
The continue statement is used to skip the rest of the current iteration and move to the next one in a loop.
Syntax:
pythonfor item in iterable:
if condition:
break # Exit the loop
if another_condition:
continue # Skip the current iteration and move to the next one
Example:
pythonnumbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number == 3:
break # Exit the loop when number is 3
if number % 2 == 0:
continue # Skip even numbers
print(number)
In this example, the break statement is used to exit the loop when number is 3, and the continue statement is used to skip even numbers.
Exception handling allows you to handle errors and exceptions gracefully. It involves the try
, except
, else
, and finally blocks
.
Syntax:
pythontry:
# Code that may raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to execute if no exception is raised
finally:
# Code that always executes, whether an exception is raised or not
Example:
pythontry:
result = 10 / 0 # Attempt to divide by zero
except ZeroDivisionError:
print("Division by zero is not allowed")
else:
print("Result:", result)
finally:
print("Execution completed")
Here, an exception is raised when attempting to divide by zero, and the code uses exception handling to catch the error and provide a message.
Python provides comprehensions (list comprehensions, dictionary comprehensions, and set comprehensions) that allow you to create new data structures based on existing ones in a concise and expressive manner.
Syntax:
python# List comprehension
new_list = [expression for item in iterable if condition]
# Dictionary comprehension
new_dict = {key: value for key, value in iterable if condition}
# Set comprehension
new_set = {expression for item in iterable if condition}
Example:
pythonnumbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares)
This code uses list comprehension to create a new list squares containing the squares of the numbers in the numbers list.
These examples illustrate various aspects of control flow in Python, including making decisions, looping, handling exceptions, and using comprehensions.
Control flow structures allow you to create programs that can perform different actions based on conditions and iterate through data efficiently.