Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Assignment-06 (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):


return length * width
area = calculate_area(5, 6)
print(area)

Add a docstring to the calculate_area function explaining its purpose.

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.

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

Write a function is_prime that checks if a given number is prime.

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

Implement a function factorial to calculate the factorial of a given number.

In [ ]: def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

Create a function print_pattern to print a specific pattern of stars.

In [ ]:
def print_pattern(rows):
for i in range(1, rows + 1):
print("*" * i)

Write a function multiply_numbers with default values for its parameters.

In [ ]: def multiply_numbers(num1=1, num2=1):


return num1 * num2

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

Write a function that uses a variable from the enclosing scope.

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()

# Call the outer function


outer_function()

Create a global variable and modify it inside a function.

In [ ]:
# Define a global variable
global_var = 5

# Define a function that modifies the global variable


def modify_global():
global global_var
global_var += 10

# 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)

Write a lambda function to calculate the cube of a number.

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.

In [ ]: # Define a list of numbers


numbers = [1, 2, 3, 4, 5]

# Use map with a lambda function to calculate the squares of each number
squared_numbers = map(lambda x: x ** 2, numbers)

# Convert the map object to a list and print the result


print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]

Use a lambda function with the filter function to filter even numbers from a list.

In [ ]: # Define a list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter with a lambda function to filter even numbers


even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Convert the filter object to a list and print the result


print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]

Apply a lambda function with the reduce function to find the product of a list.

In [ ]:
from functools import reduce

# Define a list of numbers


numbers = [1, 2, 3, 4, 5]

# Use reduce with a lambda function to find the product of the list
product = reduce(lambda x, y: x * y, numbers)

# Print the result


print(product) # Output: 120

Sort a list of tuples based on the second element using a lambda function.

In [ ]: # Define a list of tuples


my_list = [(1, 5), (2, 3), (3, 7), (4, 2), (5, 6)]

# 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])

# Print the sorted list


print(sorted_list) # Output: [(4, 2), (2, 3), (1, 5), (5, 6), (3, 7)]
Demonstrate the use of the zip function with two lists.

In [ ]: # Define two lists


list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']

# Use the zip function to combine the lists into tuples


zipped = zip(list1, list2)

# Convert the result to a list and print it


print(list(zipped)) # Output: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

Implement a generator function that generates Fibonacci numbers.

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

# Create a generator object for Fibonacci numbers


fib_gen = fibonacci()

# Generate and print the first 10 Fibonacci numbers


for _ in range(10):
print(next(fib_gen))

Use a generator expression to create a sequence of squares.

In [ ]:
# Define a generator expression to generate squares
squares_gen = (x ** 2 for x in range(1, 11))

# Iterate over the generator and print each square


for square in squares_gen:
print(square)

Write a function that uses the yield statement to produce a generator.

In [ ]:
def generate_numbers(n):
for i in range(1, n + 1):
yield i

numbers_gen = generate_numbers(5)

for number in numbers_gen:


print(number)
Explain the difference between iterators and generators in Python.

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()

# Call the outer function


outer_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.

In [ ]: # Create a list of strings containing both uppercase and lowercase words


words = ['Apple', 'banana', 'grape', 'Orange', 'kiwi']

# Sort the list in a case-insensitive manner using lambda function with so


sorted_words = sorted(words, key=lambda x: x.lower())

# Print the sorted list


print(sorted_words)

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()

# Print the first 10 prime numbers


for _ in range(10):
print(next(prime_gen))

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

# Apply the measure time decorator to function


@measure_time
def my_function(n):
# Simulate some computation
for _ in range(n):
pass

# Call the decorated function


my_function(1000000)

You might also like