4th Python Functions, Modules and Packages
4.1 Use of Python built-in functions (e.g type/ data conversion functions, math
functions etc.)
Q.1.Explain four built-in list functions. - 4 mks
Python provides a wide range of built-in functions that simplify programming tasks. These
functions can be categorized based on their purposes, such as type conversion, mathematical
operations, etc.
1. Type Conversion Functions
These functions allow conversion between data types.
int(x)
c): Converts x to an integer.
int("42") # Output: 42
float(x): Converts x to a float.
float("3.14") # Output: 3.14
str(x): Converts x to a string.
str(123) # Output: '123'
bool(x): Converts x to a boolean.
bool(0) # Output: False
bool(1) # Output: True
2. Math Functions
Python provides basic mathematical functions in the standard library.
abs(x): Returns the absolute value of x.
abs(-5) # Output: 5
round(x[, n]): Rounds x to n decimal places.
round(3.14159, 2) # Output: 3.14
sum(iterable, start=0): Returns the sum of items in an iterable.
sum([1, 2, 3]) # Output: 6
3. Utility Functions
These functions provide utility operations.
type(obj): Returns the type of an object.
type(42) # Output: <class 'int'>
len(s): Returns the length of an object.
len("hello") # Output: 5
range(start, stop): Returns a sequence of numbers.
list(range(1, 5)) # Output: [1, 2, 3, 4]
id(obj): Returns the memory address of an object.
id(42) # Output: e.g., 140377950710080
input(prompt): Accepts user input.
name = input("Enter your name: ")
4.2 User defined functions: Function definition, Function calling, function
arguments and parameter passing, Return statement, Scope of Variables:
Global variable and Local Variable.
Q.1. Explain following functions with example: - 4 mks
i) The open( ) function
ii) The write( ) function
i) The open() Function
The open() function in Python is used to open a file and return a file object, which allows you to
interact with the file (reading, writing, etc.). It takes at least one argument, the file path, and
optionally a mode (to specify how the file should be opened).
ii) The write() Function
The write() function is used to write data to a file. It is available after opening a file in a write or
append mode ('w', 'a')
3. Function Arguments and Parameter Passing
● Arguments: Values provided to the function when it is called.
● Parameters: Variables defined in the function definition that receive the arguments.
● Types of Arguments
4. Retty6urn Statement
● The return statement is used to exit a function and optionally pass an expression or value
back to the caller. This allows functions to produce output.
5. Scope of Variables
Q.1. Explain Local and Global variable. - 2 mks
Local Scope: A variable defined inside a function is local to that function and cannot be accessed
outside.
def f():
x = 10 # Local variable
print(x)
f()
# print(x) # Error, x is not accessible outside f()
Global Scope: A variable defined outside any function is global and can be accessed inside
functions, but to modify it inside a function, you need to use the global keyword.
x = 10 # Global variable
def f():
global x
x = 20 # Modify global variable
f()
print(x) # Output: 20
Q.2.Write the output for the following if the variable course =
“Python”
>>> course [ : 3 ]
>>> course [ 3 : ]
>>> course [ 2 : 2 ]
>>> course [ : ]
>>> course [ -1 ]
>>> course [ 1 ] - 6 mks
4.3 Modules: Writing modules, importing modules, importing objects from
modules, Python built in modules (e.g. Numeric and mathematical module,
Functional Programming Module) Namespace and Scoping.
Modules in Python are files that contain reusable pieces of code, functions, classes, and
variables. They provide a way to organize and structure code for reusability and better
maintainability.
3. Importing Specific Objects Using
This approach allows you to import specific functions, classes, or variables from a module,
rather than the entire module.
1.1 math Module
The math module provides mathematical functions like square roots, logarithms, trigonometry,
and constants
1.2 cmath Module
Similar to the math module, but for complex numbers. It includes functions for complex math,
such as computing square roots and logarithms of complex numbers.
1.3 random Module
The random module is used to generate random numbers. It supports various randomization
functions like generating random integers, floats, and random selections from a sequence.
1.4 statistics Module
The statistics module provides functions to calculate mathematical statistics of data, like
mean, median, mode, and standard deviation.
1.5 datetime Module
The datetime module provides classes for manipulating dates and times.
Q.1. Explain Module and its use in Python. - 4 mks
Q.2.Write a program for importing module for addition and
substraction of two numbers. - 4 mks
Q.3.Write a python program to create a user defined module that will ask
your program name and display the name of the program. - 4 mks
Q.4.Write python program using module, show how to write and
use module by importing it. - 4mks
Namespace and Scoping.
Q.1.State use of namespace in python. - 2 mks
Separate Variables: Different parts of your program (like inside functions or outside) can have
variables with the same name without causing problems.
Prevent Conflicts: They prevent variable names from clashing in different places in the code.
Built-in Functions: Python has a built-in namespace for things like print() and len().
Namespace
A namespace is a space where Python stores names (like variables or functions). It keeps track of
where each name belongs.
● Local Namespace: Variables inside a function.
● Global Namespace: Variables outside any function (can be used anywhere in the
program).
● Built-in Namespace: Predefined names like print() or len().
Scoping
Scoping defines where you can access a variable. It tells Python where a variable can be used.
● Local: Inside a function.
● Global: Outside any function (used throughout the program).
● Enclosing: Inside outer functions but outside inner ones.
4.4 Python Packages: Introduction, Writing Python packages, Using standard
(e.g. math, Numpy, matplotlib, pandas etc.) and user defined packages
Q.1.Write a program illustrating use of user defined package in python. - 6
Mks
Introduction
Writing your own Python packages helps organize and reuse code effectively. A Python
package is a collection of modules that are organized in directories. Each package can contain
multiple modules (Python files) and sub-packages.Writing Python packages
Create a Directory for your package, e.g., my_package/.
Add Python Modules (files with .py extension) inside the directory:
● Example: module1.py, module2.py.
Create an __init__.py file to mark the directory as a package. This can be empty or contain
code to initialize the package.
Use Your Package by importing it in your Python script.
Q.2.Write use of matplotlib package in python - 2 mks
Matplotlib is a powerful library in Python used for creating various types of plots and charts. It's
widely used for data visualization.
Common Plot Types:
Using Standard and User-Defined Packages in Python
1. Using Standard Python Packages
Python comes with many pre-installed packages (known as standard libraries) that provide a
wide range of functionalities like mathematical operations, data manipulation, visualization, etc.
Here are some examples of how to use popular standard packages:
Q.1. Explain Numpy package in detail. 4 mks
NumPy is a key package in Python. It helps you work with arrays and matrices, which are
collections of numbers, and provides many tools to perform mathematical operations on
them efficiently.
1. NumPy Arrays
● Arrays: Think of arrays as grids of numbers. You can create a one-dimensional
array (like a list of numbers) or a multi-dimensional array (like a table of
numbers).
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]
2. Doing Math with Arrays
● You can perform mathematical operations on entire arrays at once, which makes
your code shorter and faster.
arr = np.array([1, 2, 3, 4])
print(arr * 2) # Output: [2 4 6 8]
3. Accessing Parts of Arrays
● You can easily get parts of an array, like selecting a row from a table or a slice of a
list.
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4]) # Output: [2 3 4]