PWP_Chapter 4

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

CHAPTER 4 PYTHON FUNCTIONS, MODULES AND PACKAGE (WEIGHTAGE :14

MARKS)

4.1 Use of Python built-in functions (e.g. type/data conversion functions,math functions
etc)
1. Explain Data Conversion functions in python.(Question given by sir) (2 Marks)
➢ Data conversion functions are used to convert data from one type to another.
➢ int(): This function converts a value to an integer type.
For example: x = int("10") # Converts the string "10" to an integer.
➢ float(): This function converts a value to a floating-point number.
For example: y = float("3.14") # Converts the string "3.14" to a float.
➢ str(): This function converts a value to a string.
For example: z = str(42) # Converts the integer 42 to a string
➢ bool(): This function converts a value to a boolean.
For example: a = bool(0) # Converts the integer 0 to False.

2. Use of any four methods in math module (Sample paper) (2 Marks)


➢ The math module in Python is a built-in module that provides a collection of mathematical
functions and constants.
➢ Various Functions of math module are :
• math.sqrt(x): Returns the square root of a number x.
example : import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0
• math.pow(x, y): Returns the value of x raised to the power of y.
example : import math
result = math.pow(2, 3)
print("2 raised to the power of 3:", result) # Output: 8.0
• math.ceil(x) : Returns the smallest integer greater than or equal to x
Example : import math
result = math.ceil(3.2)
print("Ceiling of 3.2 is:", result) # Output: 4
• math.floor(x): Returns the largest integer less than or equal to x.
example :
import math
result = math.floor(3.7)
print("Floor of 3.7 is:", result) # Output: Floor of 3.7 is: 3

3. Describe any two data conversion function (S 23) (2 Marks)


Data conversion functions are used to convert data from one type to another.
int(): This function converts a value to an integer type.
For example: x = int("10") # Converts the string "10" to an integer.
float(): This function converts a value to a floating-point number.
For example: y = float("3.14") # Converts the string "3.14" to a float.
4. Shows the use of reduce function with an example. (Question given by sir) (2 Marks)
➢ The reduce() function is a part of functools module.
➢ The reduce() function continuously applies a function to pairs of elements in a sequence until only one
value remains
➢ Example :
Using reduce(0 function to find maximum value in the list :

from functools import reduce


num = [3,7,2,9,1,6]
def find_max(x,y) :
return x if x > y else y
max_value = reduce(find_max,num)
print(“Maximum value in the list is:”,max_value)

output :
Maximum value in the list is : 9

5. Describe mkdir() function. (S 23) (2 Marks)


➢ The mkdir() function in Python's os module creates a new directory with a specified name.
➢ It takes the directory path as an argument and can also specify permissions.
➢ Syntax :
import os
os.mkdir(path, <mode=0o777>, < dir_fd=None>)

➢ Example :
import os
# Specify the directory name
directory_name = "new_directory"
# Create the directory
os.mkdir(directory_name)
print("Directory created successfully!")

6. Explain type conversion of variable in python. (Question given by sir) (4 Marks)


➢ Type conversion of variable means changing the datatype of a variable from one datatype to another.
➢ In Python there are two type of type conversion :

• Implicit Type Conversion :


i) In Implicit type conversion of data types of variable in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
ii) Example :
x = 5 # integer
y = 2.5 # float
z = x + y # implicit conversion of x to float
print(z) # Output: 7.5

• Explicit Type Conversion :


i) Explicit type conversion, also known as type casting, is when you manually change the data
type of a variable using built-in functions.
ii) Python provides several built-in functions for explicit type conversion:
▪ int(): Converts a value to an integer data type.
▪ float(): Converts a value to a floating-point data type.
▪ str(): Converts a value to a string data type.
▪ bool(): Converts a value to a boolean data type.
▪ list(), tuple(), set(): Convert iterable objects (e.g., lists, tuples, sets) to other data
types.
▪ dict(): Converts a sequence of key-value pairs into a dictionary data type.
iii) Example :
a = 10.75 # float
b = int(a) # explicit conversion of a to integer
print(b) # Output: 10

7. Explain any four Python’s Built in Function with example ( S 23) (4 Marks)
➢ Python’s Built in Functions are :
i) len() : This function returns the length of an object such as a string, list, tuple, dictionary, etc.
example :
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5

ii) type(): This function returns the type of an object.


Example :
my_integer = 10
print(type(my_integer)) # Output: <class 'int'>

iii) max(): This function returns the maximum value among the arguments provided or the maximum
value in an iterable.
Example :
print(max(10, 20, 30)) # Output: 30

iv) min(): This function returns the minimum value among the arguments provided or the minimum
value in an iterable.
Example :
print(min(10, 20, 30)) # Output: 10

8. Write a python program to demonstrate the use of any six built in mathematical functions (W 23)
(6 Marks)

import math
# 1. Absolute value
num1 = -10
abs_result = abs(num1)
print("Absolute value of", num1, "is:", abs_result)

# 2. Exponential function (e^x)


x=2
exp_result = math.exp(x)
print("Exponential of", x, "is:", exp_result)

# 3. Square root
num2 = 25
sqrt_result = math.sqrt(num2)
print("Square root of", num2, "is:", sqrt_result)

# 4. Trigonometric functions (sine, cosine, tangent)


angle_rad = math.radians(45) # Convert angle to radians
sin_result = math.sin(angle_rad)
cos_result = math.cos(angle_rad)
tan_result = math.tan(angle_rad)
print("Sine of 45 degrees is:", sin_result)
print("Cosine of 45 degrees is:", cos_result)
print("Tangent of 45 degrees is:", tan_result)

# 5. Logarithmic function (base 10)


num3 = 1000
log_result = math.log10(num3)
print("Logarithm base 10 of", num3, "is:", log_result)

# 6. Ceiling and floor functions


num4 = 4.6
ceil_result = math.ceil(num4)
floor_result = math.floor(num4)
print("Ceiling of", num4, "is:", ceil_result)
print("Floor of", num4, "is:", floor_result)

output :
Absolute value of -10 is: 10
Exponential of 2 is: 7.38905609893065
Square root of 25 is: 5.0
Sine of 45 degrees is: 0.7071067811865476
Cosine of 45 degrees is: 0.7071067811865476
Tangent of 45 degrees is: 0.9999999999999999
Logarithm base 10 of 1000 is: 3.0
Ceiling of 4.6 is: 5
Floor of 4.6 is: 4

4.2 User Defined Functions : Function definition,Function calling,function


arguments,and parameter passing,Return statement , Scope of variables : Global
Variable and Local Variable
1. Describe User-defined Function in python. (Question given by sir) (2 Marks)
➢ A function is a set of statements that take inputs,do some specific computation,and produce output.
➢ All the functions that are written by any of us come under the category of user defined functions.
➢ Syntax :
def function_name() :
Statements
:
:
➢ Example :
def fun() :
print(“Inside function”)
fun()

output :
Inside function

2 Write different types of arguments in a function.(Question given by sir) (2 Marks)


➢ Different types of arguments in Function are :
• Required arguments.
• Keyword arguments
• Default arguments
• Variable length arguments

3 State the use of keyword global with simple example. (Question Given by sir) ( 2 Marks)
➢ A global keyword is used to create global variables in Python from a non-global scope, i.e. inside
a function.
➢ Example :
x = 10 # global variable

def modify_global():
global x # declaring x as global
x = 20

modify_global()
print(x) # Output will be 20
4. Define function in python (Sample Paper) (2 Marks)
➢ In Python, a function is a block of reusable code that performs a specific task.
➢ Functions allow you to break down your program into smaller, manageable parts, making your
code more organized, readable, and reusable.
➢ Syntax for declaring a function :
def function_name(parameters) :
# Function body
[return value]
➢ Example : Adding two numbers through the function
def add_numbers(a, b):
return a + b

result = add_numbers(3, 5)
print("The sum is:", result)

output :
8

5 Explain local and global variable (S 22) (2 Marks)


➢ Local Variables :-
• Local variables are declared inside a function or block of code and are accessible only within
that specific function or block.
• Once the function or block execution completes, the local variable is destroyed, and its
value cannot be accessed from outside that scope.
• Example :
def my_function():
x = 10 # local variable
print("Inside function:", x)

my_function()

➢ Global Variables :-
• Global variables are declared outside of any function or block of code and can be accessed
from any part of the program, including inside functions.
• They can be modified and assigned new values from any part of the program.
• If a variable is modified inside a function without being declared as global, Python treats it
as a new local variable within that function's scope.
• Example :
y = 20 # global variable

def my_function():
print("Inside function:", y)

my_function()
print("Outside function:", y)

6 Write a function that takes single character and prints „character is vowel‟ if it is
vowel,character is not vowel‟ otherwise. (Question given by sir) (4 marks)
➢ def check_vowel():
# Take input from the user
char = input("Enter a single character: ")
# Check if the character is a vowel
if char in ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']:
print("Character is vowel")
else:
print("Character is not vowel")

# Call the function


check_vowel()
Output :
Enter a single character: A
Character is vowel

9. Write a python program to calculate factorial of given number using recursive function. (Question
given by sir) (4 marks)
➢ def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: multiply n by factorial of (n-1)
else:
return n * factorial(n - 1)

# Take input from the user


num = int(input("Enter a number: "))

# Check if the input is non-negative


if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print("Factorial of", num, "is:", result)
Output :
Enter a number: 5
Factorial of 5 is: 120

8 .Write a python program to find reverse of a given number using user defined function.(Question
given by sir) (4 marks)
➢ def reverse_number(num):
# Initialize a variable to store the reverse of the number
reverse = 0

# Iterate through each digit of the number


while num > 0:
# Extract the last digit of the number
digit = num % 10
# Append the digit to the reverse number
reverse = (reverse * 10) + digit
# Remove the last digit from the number
num = num // 10

# Return the reverse of the number


return reverse

# Take input from the user


number = int(input("Enter a number: "))
# Call the user-defined function to find the reverse of the number
reverse = reverse_number(number)
# Print the reverse of the number
print("Reverse of the number:", reverse)

Output :
Enter a number: 1234
Reverse of the number: 4321
9. Comparing between local and global variable (Sample paper) ( 4 marks)

Comparision Basis Global Variable Local Variable
Definition declared outside the declared within the
functions functions
Lifetime They are created the They are created when the
execution of the program function starts its
begins and are lost when execution and are lost
the program is ended when the function ends
Data Sharing Offers Data Sharing It doesn’t offers Data
Sharing
Scope Can be access throughout Can access only
the code inside the function
Parameters needed parameter passing is not parameter passing is
necessary necessary
Storage A fixed location selected They are kept on the
by the compiler stack
Value Once the value changes it once changed the variable
is reflected throughout the don’t affect other
code functions of the program

10 Write a program to add two numbers using function (W 23) (4 marks)


➢ def add(a,b):
return a + b
a = int(input("Enter 1st Number :"))
b = int(input("Enter 2nd Number :"))
result = add(a,b)
print("Addition of ",a," and ",b,"is : ",result)

output :
Enter 1st Number :10
Enter 2nd Number :20
Addition of 10 and 20 is : 30

11. Compare local and global variable ( W 23) ( 4 Marks)



Comparision Basis Global Variable Local Variable
Definition declared outside the declared within the
functions functions
Lifetime They are created the They are created when the
execution of the program function starts its
begins and are lost when execution and are lost
the program is ended when the function ends
Data Sharing Offers Data Sharing It doesn’t offers Data
Sharing
Scope Can be access throughout Can access only
the code inside the function
Parameters needed parameter passing is not parameter passing is
necessary necessary
Storage A fixed location selected They are kept on the
by the compiler stack
Value Once the value changes it once changed the variable
is reflected throughout the don’t affect other
code functions of the program
12. Write a python program to calculate sum of digit of given number using function (S 23) (4
marks)
➢ def sumofdigits(a):
sum = 0
for i in range(len(a)):
sum = sum + int(a[i])
return sum
a = input("Enter a Number :")
result = sumofdigits(a)
print("Sum of Digits of ",a,"is : ",result)

output :
Enter a Number :123
Sum of Digits of 123 is : 6

13. Explain how to use user defined function in python with example ( S 22) (4 marks)
➢ i) User-defined functions allow you to create your own functions in Python to perform specific tasks.
ii) syntax for declaring user defined function in python is :
def function_name(parameters):
# Function body
# Perform tasks
return value # (optional)
iii) After declaring a function we need to call the function.
iv) Example :
def fun() :
print(“Inside function”)
fun()

output :
Inside function

14. What is local and global variables? Explain with appropriate example. ( W 22) (4 marks)
(i) Local Variables :-
• Local variables are declared inside a function or block of code and are accessible only within that
specific function or block.
• Once the function or block execution completes, the local variable is destroyed, and its value
cannot be accessed from outside that scope.
• Example :
def my_function():
x = 10 # local variable
print("Inside function:", x)

my_function()
(ii) Global Variables :-
• Global variables are declared outside of any function or block of code and can be accessed from
any part of the program, including inside functions.
• They can be modified and assigned new values from any part of the program.
• If a variable is modified inside a function without being declared as global, Python treats it as a
new local variable within that function's scope.
• Example :
y = 20 # global variable

def my_function():
print("Inside function:", y)

my_function()
print("Outside function:", y)

15. Write a python program to calculate factorial of given number using function ( Sample paper)
(6 Marks)
➢ def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: multiply n by factorial of (n-1)
else:
return n * factorial(n - 1)
# Take input from the user
num = int(input("Enter a number: "))
# Check if the input is non-negative
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print("Factorial of", num, "is:", result)

Output :
Enter a number: 5
Factorial of 5 is: 120

4.3 Modules : Writing modules, importing modules,importing objects from modules,


Python built in modules (e.g Numeric and mathematical , Functional programming
module ) Namespacing and Scoping .
1. Define Module in python? How to create a module and use it. (Question given by sir)(2 marks)
➢ Python modules are files containing Python code that defines functions,classes and variables, and
executable code.
➢ To create a Python module :
• Create a .py file with desired module name .
• Write code inside it(Functions,classes, variables)
• Save the file.
➢ To use it :
• Import module using import module_name.
• Access its contents using module_name.function(),module_name.variable,etc.

2. Explain from...import statement. (Question given by sir)(2 marks)


➢ The from..import statement in Python allows us to pick and choose specific elements (like
functions,variables and classes)from a module and bring them directly into the code .
➢ We can use these elements without having to reference the module name every time.
➢ Example :
from math import sqrt
square_root = sqrt(25)
print(“Square root of 25 is :”,square_root)

output :
square root of 25 is : 5

3. State the use of namespace in python (Sample Paper ) ( 2 Marks)


➢ i)A namespace is a system to have a unique name for each and every object in python.
ii) An object might be a variable or a method.
iii) Python itself maintains a namespace in the form of a python
dictionary.
iv) Name means an unique identifier while space talks something
related to scope.
v) Types of namespace are :
• Local Namespace
• Global Namespace
• Buitl in Namespace

4. Use of any four methods in math module (Sample paper) ( 2 Marks)


➢ The math module in Python is a built-in module that provides a collection of mathematical functions
and constants.
➢ Various Functions of math module are :
• math.sqrt(x): Returns the square root of a number x.
example : import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0
• math.pow(x, y): Returns the value of x raised to the power of y.
example : import math
result = math.pow(2, 3)
print("2 raised to the power of 3:", result) # Output: 8.0
• math.ceil(x) : Returns the smallest integer greater than or equal to x
Example : import math
result = math.ceil(3.2)
print("Ceiling of 3.2 is:", result) # Output: 4
• math.floor(x): Returns the largest integer less than or equal to x.
example :
import math
result = math.floor(3.7)
print("Floor of 3.7 is:", result) # Output: Floor of 3.7 is: 3

5. Explain use of namespace in python (Sample paper) ( 2 Marks)


➢ i) A namespace is a system to have a unique name for each and
every object in python.
ii) An object might be a variable or a method.
iii) Python itself maintains a namespace in the form of a python
dictionary.
iv) Name means an unique identifier while space talks something
related to scope.
v) Types of namespace are :
• Local Namespace
• Global Namespace
• Buitl in Namespace
6. Explain python built in module (Question given by sir)(4 Marks)
i)Numeric and Mathematical Module. ii) Functional Programming Module
➢ i) Numeric and Mathematical Module (math) :-
• The math module provides functions for various mathematical operations, including
trigonometry, logarithms, exponentiation, and more.
• It's particularly useful for performing advanced mathematical calculations beyond basic
arithmetic.
• Example :
import math

def calculate_area(radius):
return math.pi * math.pow(radius, 2)

radius = 5
area = calculate_area(radius)
print("Area of the circle with radius", radius, "is", area)

output :
Area of the circle with radius 5 is 78.53981633974483

ii) Functional Programming Module


• This modules provide functions and classes that support a
functional programming style and general operations on
callable.
• Following modules are used here
Itertools Module: Offers tools for manipulating sequences during traversal. chain()
function combines multiple iterables into one sequence.
Functools Module: Facilitates writing reusable code. partial() function creates
specialized versions of functions with pre-set arguments.
Operator Module: Provides functions equivalent to Python's operators, useful for

7.Describe module in python with its advantages (Sample paper) (4 Marks)


i) A module in Python is simply a file containing Python statements and definitions. It typically consists of
functions, classes, and variables that perform specific tasks or define reusable components.
ii) Modules can be imported into other Python scripts or programs to access their functionality.
iii) Example :
Calculating the square root of a number using math module.

import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0
iv) Advantages :
▪ Code Organization: Modules organize code into logical units, enhancing readability and
maintainability.
▪ Code Reusability: Modules facilitate the reuse of functions and classes across different
parts of a project, reducing redundancy.
▪ Namespace Isolation: Each module has its namespace, preventing naming conflicts and
promoting modular development.
▪ Encapsulation: Modules encapsulate functionality, hiding implementation details and
promoting abstraction for easier comprehension.

10. Explain Module and its use in python ( S 23) (4 Marks)



i) A module in Python is simply a file containing Python statements and definitions. It typically
consists of functions, classes, and variables that perform specific tasks or define reusable
components.
ii) Modules can be imported into other Python scripts or programs to access their functionality.
iii) Uses of Module in python :
• Organizing Code: Modules help in organizing code by grouping related functionality
together. For example, you might have a module for handling file operations, another for
mathematical computations, and so on.

• Code Reusability: Once you've written code in a module, you can reuse it in different parts of
your program or in other programs altogether. This promotes code reuse and helps in
avoiding redundancy.

• Namespacing: Modules provide a way to create separate namespaces for different parts of
your program. This helps in avoiding naming conflicts between different variables, functions,
or classes.

• Importing: To use code from a module, you need to import it into your program using the import
statement. Once imported, you can access the functions, classes, and variables defined in the
module using dot notation (module_name.item_name).
iv) Example :
Calculating the square root of a number using math module.

import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0

11. Write a program for importing module for addition and subtraction of two numbers ( S 22)(4
Mrks)
➢ i) First, create a Python module named math_operations.py # math_operations.py

def add(a, b):


return a + b

def subtract(a, b):


return a – b

ii) Then, create another Python script in the same directory and import the math_operations
module to perform addition and subtraction:

# main.py

# Importing the math_operations module


import math_operations

# Input two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform addition and subtraction using functions from the imported module
sum_result = math_operations.add(num1, num2)
difference_result = math_operations.subtract(num1, num2)

# Display the results


print("Sum:", sum_result)
print("Difference:", difference_result)

output :
Enter the first number : 10
Enter the second number :20
Sum : 30
Difference : -10

12. Explain module. How to define module. ( W 22)(6 Marks)



i) A module are primarily .py files that represents group of classes, methods and functions.
ii) In python there are several built-in modules. Just like these modules we can create our own
modules and use whenever we need them.
iii) Once a module is created, any programmer in the project team can use that module. Hence
modules will make software development easy and faster.
iv) Advantages of modules :-
Reusability
Simplicity
Scoping
v) Defining Module:
Follow the following steps to definemodules:
• Create a first file as a python program with extension as .py. This is your module file where
we can write a function which performs some task.

• Create a second file in the same directory called main file where we can import the module to
the top of the file and call the function.

vi) Example :

Create p1.py file and add the below code in the file

def add(a,b):
result=a+b
return result

def sub(a,b):
result=a-b
return result

def mul(a,b):
result=a*b
return result

def div(a,b):
result=a/b
return result

Create p2.py file I same directory where p1.py is created and


add the below code in the file.

import p1
print("Addition= ",p1.add(10,20))
print("Subtraction= ",p1.sub(10,20))
print("Multiplication= ",p1.add(10,20))
print("Division= ",p1.add(10,20))
Output:
Addition= 30
Subtraction= -10
Multiplication= 30
Division= 30

4.4 Python packages : Introduction,Writing Python packages,Using Standard (e.g


math,scipy,Numpy,matplotlib,pandas,etc,) and user defined pacakges.
13. Use of Numpy (Sample Paper) (2 Marks)
➢ NumPy is a fundamental package for scientific computing with Python.
➢ It provides support for multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays efficiently.
➢ Example :
import numpy as np

# Create a NumPy array


arr = np.array([1, 2, 3, 4, 5])

# Perform a mathematical operation


result = arr * 2

# Print the result


print(result)

In this example, we import NumPy as np, create a one-dimensional array [1, 2, 3, 4, 5], multiply each
element by 2, and print the resulting array [2, 4, 6, 8, 10].

14. List and explain any two standard packages of python (W 23)(2 Marks)
➢ Any Two Standard Packages are :
• Numpy Package : NumPy is a fundamental package for scientific computing with Python. It
provides support for multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays efficiently.
• Pandas Package : This package provides high-performance, easy-to-use data structures and
data analysis tools for the Python programming language. It's particularly well-suited for
working with structured, tabular data, such as CSV files or SQL tables.

15. Define Package? Write the steps to create a package in python? (Question given by sir) ( 4 Marks)
➢ i) A package is a hierarchical file directory structure that defines
a single python application environment that comprises of
modules and subpackages and so on.
ii) Packages allow for a hierarchical structuring of the module
namespace using dot notation.
iii) To create a package in Python, we need to follow these three
simple steps:
1) First, we create a directory and give it a package name, preferably related to its operation.
2) Then we put the classes and the required functions in it.
3) Finally we create an __init__.py file inside the directory, to let Python know that the directory
is a package.
iv) Example :
Create a directory named mypkg and create a __init__.py file and save in the mypkg directory so
that mypkg will be considered as package.
• Create file p1.py in the mypkg directory and add this code
def m1():
print("First Module")
• Create file p2.py in the mypkg directory and add this code
def m2():
print("second module")
• Create file pkgsample.py and add this code
from mypkg import p1,p2
p1.m1()
p2.m2()

Output-
First Module
second module
4. Explain the following package with suitable example (Question given by sir) ( 4 marks)
i)numpy ii) scipy iii) pandas iv) matplotlib
➢ i) NumPy:-
• NumPy is a fundamental package for scientific computing with Python. It provides support for
multi-dimensional arrays and matrices, along with a collection of mathematical functions to
operate on these arrays efficiently.
• Example :
import numpy as np

# Create a NumPy array


arr = np.array([1, 2, 3, 4, 5])

# Perform a mathematical operation


result = arr * 2

# Print the result


print(result)

output :
[ 2 4 6 8 10]
ii) SciPy:-
• SciPy is built on top of NumPy and provides additional functionality for scientific computing. It
includes modules for optimization, interpolation, integration, linear algebra, signal processing,
and more.
• Example :
from scipy.integrate import quad

# Define the mathematical function to integrate


def integrand(x):
return x**2

# Integrate the function from 0 to 1


result, error = quad(integrand, 0, 1)

print("Result of integration:", result)


print("Estimated error:", error)

output :
Result of integration: 0.33333333333333337
Estimated error: 3.700743415417189e-15

iii)pandas :
• Pandas is a powerful data analysis and manipulation library for Python. It provides data structures
like DataFrame and Series, along with tools for reading and writing data from various file formats,
data cleaning, reshaping, and analysis.
• Example :
import pandas as pd

# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}

df = pd.DataFrame(data)

# Display the DataFrame


print(df)

output :
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston

iv) matplotlib :
• Matplotlib is a plotting library for Python that produces high-quality visualizations. It provides a
MATLAB-like interface for creating a variety of plots, including line plots, scatter plots, bar plots,
histograms, and more.
• Example :
import matplotlib.pyplot as plt

# Data for plotting


x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot the data


plt.plot(x, y)

# Show the plot


plt.show()

5.Write a program illustrating use of user defined package in python ( S 22) ( 4 Marks)

1) Create a directory named mypkg1 and create a __init__.py file and save in the mypkg1 directory so
that mypkg1 will be considered as package.
2) Create modules message.py and mathematics.py with following code:

message.py

def sayhello(name):
print("Hello " + name)
return

mathematics.py

def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y

3) Create p1.py with the code given

p1.py

from mypkg1 import mathematics


from mypkg1 import message
message.sayhello("Amit")
x=mathematics.power(3,2)
print("power(3,2) :",x)

Output
Hello Amit
power(3,2) : 9

6. Explain package Numpy with example ( S 22) ( 4 Marks)



1) NumPy is the fundamental package for scientific computing with python.
2) NumPy stands for “Numeric Python”.
3) It provides a high performance multidimensional array object and tools for working with these
arrays.
4) Using NumPy , a developer can perform the following operations:
1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape manipulation.
3. Operations related to linear algebra.
4. NumPy has in-built functions for linear algebra and random number generation.
5) Example :
reshape operation using python numpy operation.

import numpy as np
arr=np.array([[1,2,3],[4,5,6]])
a=arr.reshape(3,2)
print(a)

Output:
([[1,2],
[3,4],
[5,6]])

You might also like