Functions
Functions
Functions
Change the notebook name with your name and Roll Number.
Try this as your own, no chatgpt (it's for your learning)
after completing the assignment, submit this book on google class room.
Write a function named add_numbers that takes two parameters and returns their sum.
In [ ]:
def add_numbers(num1, num2):
return num1 + num2
result = add_numbers(4, 3)
print(result)
Define a function calculate_area to compute the area of a rectangle given its length and width.
In [ ]:
def calculate_area(length, width):
"""
Calculate the area of a rectangle given its length and width.
Parameters:
length (float or int): The length of the rectangle.
width (float or int): The width of the rectangle.
Returns:
float or int: The area of the rectangle.
"""
return length * width
Create a function print_greeting that takes a name as an argument and prints a personalized greeting.
Parameters:
length (float or int): The length of the rectangle.
width (float or int): The width of the rectangle.
Returns:
float or int: The area of the rectangle.
"""
return length * width
In [ ]: def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0 or number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
In [ ]: def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
In [ ]:
def print_pattern(rows):
for i in range(1, rows + 1):
print("*" * i)
Define a function print_info that takes a variable number of arguments and prints them.
In [ ]:
def print_info(*args):
for arg in args:
print(arg)
Create a function power_of_two that accepts a number and returns its square.
In [ ]: def power_of_two(number):
return number ** 2
Define a variable inside a function and try to access it outside the function.
In [ ]:
def my_function():
x = 10
my_function()
print(x) # This will raise a NameError because 'x' is not defined in this
In [ ]:
def outer_function():
x = 10 # Variable in the enclosing scope
def inner_function():
print("Value of x from the enclosing scope:", x)
inner_function()
In [ ]:
# Define a global variable
global_var = 5
# Print the global variable before and after calling the function
print("Global variable before modification:", global_var)
modify_global()
print("Global variable after modification:", global_var)
In [ ]:
cube = lambda x: x ** 3
result = cube(5)
print(result) # Output will be 125
Use a lambda function as an argument with the map function.
# Use map with a lambda function to calculate the squares of each number
squared_numbers = map(lambda x: x ** 2, numbers)
Use a lambda function with the filter function to filter even numbers from a list.
Apply a lambda function with the reduce function to find the product of a list.
In [ ]:
from functools import reduce
# Use reduce with a lambda function to find the product of the list
product = reduce(lambda x, y: x * y, numbers)
Sort a list of tuples based on the second element using a lambda function.
# Sort the list based on the second element of each tuple using a lambda fu
sorted_list = sorted(my_list, key=lambda x: x[1])
In [ ]:
def fibonacci():
# Initialize the first two Fibonacci numbers
a, b = 0, 1
while True:
yield a # Yield the current Fibonacci number
a, b = b, a + b # Calculate the next Fibonacci number
In [ ]:
# Define a generator expression to generate squares
squares_gen = (x ** 2 for x in range(1, 11))
In [ ]:
def generate_numbers(n):
for i in range(1, n + 1):
yield i
numbers_gen = generate_numbers(5)
In [ ]: iterators are more general and can represent any stream of data, while gene
a convenient way to generate values lazily using the yield statement. Gene
memory efficiency when working with large sequences of data.
Write a Python program that includes a nested function. Inside the nested function, access a variable
from the enclosing function's scope, and explain how the scope resolution works in this case.
In [ ]:
def outer_function():
x = 10 # Variable in the enclosing function's scope
def nested_function():
print("Value of x from the enclosing scope:", x)
nested_function()
Create a list of strings containing both uppercase and lowercase words. Use a lambda function with
the sorted() function to sort the list in a case-insensitive manner.
Implement a generator function that yields prime numbers indefinitely. Use this generator to print the
first 10 prime numbers.
In [ ]: def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0 or number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
def prime_generator():
num = 2
while True:
if is_prime(num):
yield num
num += 1
# generator object
prime_gen = prime_generator()
Write a decorator function that measures the execution time of another function. Apply this decorator
to a function of your choice and print the execution time.
In [ ]:
import time
from functools import wraps
def measure_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Executiion time of {func.__name__}: {end_time - start_time}
return result
return wrapper