0% found this document useful (0 votes)
7 views32 pages

Python NumPy and Functions Guide

The document consists of a series of one-mark and five-mark questions related to Python programming, specifically focusing on NumPy, functions, file handling, and exception handling. It provides definitions, syntax, and explanations of various concepts such as NumPy arrays, function arguments, file modes, and built-in exceptions. Additionally, it emphasizes the importance of NumPy in scientific computing and its efficient array operations, mathematical functions, and integration with other libraries.

Uploaded by

praveeen291
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views32 pages

Python NumPy and Functions Guide

The document consists of a series of one-mark and five-mark questions related to Python programming, specifically focusing on NumPy, functions, file handling, and exception handling. It provides definitions, syntax, and explanations of various concepts such as NumPy arrays, function arguments, file modes, and built-in exceptions. Additionally, it emphasizes the importance of NumPy in scientific computing and its efficient array operations, mathematical functions, and integration with other libraries.

Uploaded by

praveeen291
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING R22

ONE MARK QUESTIONS


Unit-III
1. What is numPy?
Ans: NumPy is a Python library for numerical computing that provides support for
large, multi-dimensional arrays and matrices, along with a collection of mathematical
functions to operate on these arrays efficiently.
2. Write the syntax of creating 1D and 2D arrays using NumPy?
Ans:
1D array:
import numpy as np
array_1d = [Link]([1, 2, 3, 4, 5])
2D array:
import numpy as np
array_2d = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
3. What is the use of shape( ) in numPy?
Ans: The shape() function in NumPy is used to get the shape or dimensions of an
array. It returns a tuple representing the shape of the array, i.e., the number of
elements along each dimension.
4. List the attributes of numpy array?
Ans: some common attributes of NumPy arrays:
I. ndim: Number of dimensions of the array.
II. shape: Tuple of integers indicating the size of the array in each dimension.
III. size: Total number of elements in the array.
IV. dtype: Data type of the elements in the array.
V. itemsize: Size in bytes of each element of the array.
VI. nbytes: Total bytes consumed by the elements of the array.
VII. strides: Tuple of integers indicating the number of bytes to step in each
dimension when traversing the array.
5. What is the use of arange( ) in numPy?
Ans: The arange() function in NumPy is used to generate arrays with regularly
spaced values within a specified range. It is similar to Python's built-in range()
function but returns an array instead of a list.
The syntax is
[Link](start, stop, step),
where start is the starting value
stop is the ending value (exclusive)
step is the step size between values.
If start is omitted, it defaults to 0, and if step is omitted, it defaults to 1.

1
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

6. List any 5 methods used on arrays in numpy module?


Ans:
A. [Link]: Returns the shape of the array, indicating the number
of elements along each dimension.
B. [Link](): Reshapes the array into a specified shape.
C. [Link](): Computes the mean along a specified axis.
D. [Link](): Returns the maximum value of the array.
E. [Link](): Returns the minimum value of the array.

Unit-IV
1. Define function?
Ans: A function is a block of organized, reusable code that performs a specific task.
It can take input parameters, execute a sequence of statements, and optionally
return a value. Functions allow code to be modular, making it easier to
understand, reuse, and maintain.
2. What is the use of def keyword?
Ans: The def keyword in Python is used to define a function. It precedes the
function name and the parameters enclosed in parentheses. It marks the beginning
of the function definition block, where you specify what the function does when
called and how it operates on its inputs.
3. Differentiate library and user defined functions in python?
Ans: Library functions are predefined functions provided by external libraries or
modules, such as those in NumPy or the Python Standard Library. These functions
are already implemented and can be directly used in your code by importing the
respective library.

User-defined functions, on the other hand, are functions defined by the user within
their Python script or module. These functions are created using the def keyword
followed by the function name and parameters. Users define the behavior and
functionality of these functions according to their specific requirements.
4. What are the different types of function arguments?
Ans:
a. Positional arguments: These arguments are passed to a function based on their
position or order in the function call.
b. Keyword arguments: These arguments are passed with a keyword and value pair,
allowing you to specify which parameter each argument should be assigned to.
c. Default arguments: These arguments have default values specified in the function
definition. If no value is provided for these arguments during the function call, the
default value is used.
d. Variable-length arguments (*args): These arguments allow you to pass a variable
number of positional arguments to a function.
2
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

e. Keyword variable-length arguments (**kwargs): These arguments allow you to


pass a variable number of keyword arguments to a function, which are collected
into a dictionary.
5. Differentiate between local and global variables?
Ans: Local variables are defined within a function and are accessible only within
that function's scope. They are created when the function is called and destroyed
when the function exits. Local variables cannot be accessed from outside the
function.

Global variables, on the other hand, are defined outside of any function and can be
accessed from anywhere within the program. They have a global scope, meaning
they can be accessed by any function in the program. However, modifying global
variables from within a function requires the use of the global keyword to indicate
that the variable should be treated as global.
6. What is anonymous function in python?
Ans: An anonymous function in Python is a function that is defined without a
name. It is created using the lambda keyword instead of the def keyword used for
regular functions. Lambda functions can have any number of parameters but only
one expression. They are often used for simple operations or as arguments to
higher-order functions.
7. What are fruitful functions?
Ans: Fruitful functions, also known as functions that return a value, are functions in
Python that perform some computation and return a result. These functions
produce output that can be assigned to variables or used in other expressions.
They are called "fruitful" because they yield results or "fruits" of computation.
8. Write the syntax of map() function?
Ans: The syntax of the map() function in Python is:
map(function, iterable)
Here:
function is the function to be applied to each element of the iterable.
iterable is the sequence, such as a list, tuple, or string, that contains the elements
to be operated on by the function.
9. Discuss the use of filter() function?
Ans: The filter() function in Python is used to filter elements from an iterable (such
as a list, tuple, or string) based on a specified condition. It takes two arguments: a
function that returns a Boolean value (True or False) and an iterable. The function
is applied to each element in the iterable, and only the elements for which the
function returns True are included in the result.

3
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

10. What is the need of reduce() function?


Ans: The reduce() function in Python is used to apply a specified function
cumulatively to the elements of an iterable. It repeatedly applies the function to
pairs of elements from the iterable until it reduces the iterable to a single value.

The need for the reduce() function arises when you want to perform operations
like summation, multiplication, or any other binary operation on an iterable,
reducing it to a single value. It is particularly useful when you have a sequence of
values and want to perform an operation that combines them iteratively.

For example, you might want to find the sum of all elements in a list or the product
of all elements in a list. The reduce() function can help achieve this in a concise and
efficient manner.

Unit-V
1. Define file?
Ans: A file is a named collection of related information stored on a secondary
storage device, such as a hard disk, SSD, or flash drive. In computing, files are used
to store data permanently or temporarily. They can contain various types of data,
including text, images, audio, video, programs, and more. Files are organized
within directories (also known as folders) in a file system and are accessed using
file paths.
2. Write the syntax of opening a file?
Ans: The syntax of opening a file in Python is:
file_object = open(file_name, mode)
Here:
file_name is the name of the file or the path to the file.
mode specifies the purpose for which the file is opened, such as read mode
('r'), write mode ('w'), append mode ('a'), or a combination of these
with additional modifiers (e.g., 'r+', 'w+', 'a+').
3. What is the difference between text and binary files?
Ans: The main difference between text and binary files lies in how they store data:

Text files: Text files store data in a human-readable format, typically consisting of
lines of text. Each character in a text file is encoded using a character encoding
such as ASCII or UTF-8. Text files are commonly used for storing textual data like
plain text documents, configuration files, source code files, etc.

4
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Binary files: Binary files store data in a binary format, which means they contain
sequences of bytes that may represent anything, including text, numerical data,
images, audio, or any other type of data. Binary files are not human-readable and
may contain non-textual data or data encoded in a specific format. Examples of
binary files include image files (JPEG, PNG), audio files (MP3, WAV), video files
(MP4, AVI), and executable files (EXE, DLL).
4. List the various modes in which a file can be opened?
Ans: Various modes in which a file can be opened in Python are:
'r': Read mode. Opens the file for reading. The file pointer is placed at the
beginning of the file.
'w': Write mode. Opens the file for writing. If the file does not exist, it creates a
new file. If the file exists, it truncates the file to zero length.
'a': Append mode. Opens the file for appending new data. The file pointer is placed
at the end of the file. If the file does not exist, it creates a new file.
'b': Binary mode. Opens the file in binary mode, which is used for non-text files
(such as images or executable files). This mode should be used in combination with
other modes (e.g., 'rb', 'wb', 'ab').
'+': Read and write mode. Opens the file for both reading and writing. The file
pointer is placed at the beginning of the file.
5. What is the difference between compile-time and runtime errors?
Ans: Compile-time errors occur during the compilation of the code, typically due to
syntax errors, type errors, or other issues that prevent the code from being
translated into machine code. These errors prevent the program from being
compiled successfully, and the program cannot be executed until they are fixed.

Runtime errors, on the other hand, occur while the program is running. They are
also known as exceptions or run-time exceptions. Runtime errors happen when the
code is syntactically correct and successfully compiled but encounters an error
while executing, such as division by zero, accessing an out-of-bounds index in an
array, or trying to perform an operation on incompatible data types.
6. Define exception?
Ans: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. When an exceptional condition arises that
is not handled by the normal flow of control, an exception is raised.
In Python, exceptions are objects representing errors or unusual
situations that can be detected and handled by the program. They provide a way
to handle errors gracefully, allowing the program to respond to unexpected
situations and recover from them without crashing.
7. How exceptions are handled in python?
Ans: Exceptions in Python are handled using try-except blocks. Here's how
exceptions are handled in Python:

5
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

try block: The code that might raise an exception is placed within a try block.
except block: If an exception occurs within the try block, Python looks for an
except block that matches the type of the raised exception. If a matching except
block is found, the code within that block is executed to handle the exception.
If no matching except block is found, the exception propagates up the call stack
until it is caught by an appropriate except block or until it reaches the top-level of
the program, causing the program to terminate with an error message.
Here's an example:
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handle the exception
print("Error: Division by zero!")
8. Name any 5 built-in exceptions?
Ans:
1. SyntaxError: Raised when there is a syntax error in the code.
2. TypeError: Raised when an operation or function is applied to an object of
inappropriate type.
3. ValueError: Raised when a function receives an argument of the correct type
but with an inappropriate value.
4. ZeroDivisionError: Raised when division or modulo by zero occurs.
5. FileNotFoundError: Raised when attempting to access a file that does not exist.

FIVE MARK QUESTIONS


Unit-III
1. What is numpy? Why do we need numpy in python?
Ans: NumPy is a fundamental package for scientific computing in Python. It provides
support for large, multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays efficiently. NumPy is one of the
most commonly used libraries in Python for numerical computing and data analysis
tasks.
Here's why NumPy is essential and why we need it in Python:
Efficient Array Operations: NumPy provides an array object called ndarray, which is
more efficient than Python lists for performing numerical operations. NumPy's
arrays are homogeneous and contiguous in memory, allowing for efficient storage
and manipulation of large datasets.
Mathematical Functions: NumPy offers a wide range of mathematical functions that
operate element-wise on arrays, including basic arithmetic operations, trigonometric

6
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

functions, exponential and logarithmic functions, and more. These functions are
implemented in C or Fortran and are highly optimized for performance.
Broadcasting: NumPy's broadcasting feature allows for efficient element-wise
operations between arrays of different shapes and sizes. This simplifies code and
makes it more readable by eliminating the need for explicit looping over array
elements.
Linear Algebra: NumPy includes a comprehensive set of functions for linear algebra
operations, such as matrix multiplication, inversion, determinant calculation,
eigenvalue and eigenvector computation, and more. These functions are essential
for many scientific and engineering applications.
Random Number Generation: NumPy provides functions for generating random
numbers from various probability distributions. These functions are useful for tasks
such as random sampling, generating synthetic data, and simulating stochastic
processes.
Integration with Other Libraries: NumPy is the foundation for many other scientific
computing libraries in Python, such as SciPy, pandas, Matplotlib, and scikit-learn.
These libraries build on top of NumPy's array functionality and extend it with
additional features for specific domains, such as statistics, data analysis,
visualization, and machine learning.
Memory Efficiency: NumPy's arrays are memory-efficient compared to Python lists,
especially for large datasets. NumPy uses fixed-size data types and stores arrays in
contiguous memory blocks, reducing memory overhead and improving cache
locality.
Interoperability with Existing Code: NumPy provides interoperability with existing
code written in languages like C, C++, and Fortran. It allows Python code to
seamlessly integrate with legacy codebases and libraries written in these languages,
enabling high-performance computing and scientific research.
2. Explain how to create an array using numpy module?
Ans: In Python, you can create new datatypes, called arrays using the NumPy
package. NumPy arrays are optimized for numerical analyses and contain only a
single data type.
Step-by-Step Guide to Creating an Array using NumPy:
1. Install NumPy (if not already installed)
Ensure you have NumPy installed in your Python environment. You can install it
using pip if necessary:
pip install numpy
2. Import NumPy
Begin by importing the NumPy module. It’s common practice to import it with the
alias np:

import numpy as np

7
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

3. Creating Arrays
There are several ways to create arrays in NumPy:
a. From a Python List
You can create a NumPy array from a Python list using the [Link]() function.
python_list = [1, 2, 3, 4, 5]
numpy_array = [Link](python_list)
print(numpy_array)
Output:
[1 2 3 4 5]
b. Using Built-in Functions
NumPy provides various functions to create arrays of different shapes and types.
[Link](shape): Creates an array filled with zeros.
Example:
zeros_array = [Link]((3, 3))
print(zeros_array)
Output:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[Link](shape): Creates an array filled with ones.
Example:
ones_array = [Link]((2, 4))
print(ones_array)
Output:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[Link](start, stop, step): Creates an array with a range of values.
Example:
range_array = [Link](0, 10, 2)
print(range_array)
Output:
[0 2 4 6 8]
[Link](start, stop, num): Creates an array with a specified number of elements
between a start and stop value, inclusive.
Example:
linspace_array = [Link](0, 1, 5)
print(linspace_array)
Output:
[0. 0.25 0.5 0.75 1. ]
[Link](shape): Creates an array filled with random values between 0
and 1.

8
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Example:
random_array = [Link]((2, 3))
print(random_array)
Output:
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]]
4. Array Properties and Methods
Once you have created an array, you can explore its properties and methods. Some
useful properties are:
[Link]: Returns the shape of the array.
[Link]: Returns the data type of the array elements.
[Link]: Returns the total number of elements in the array.
Example:
array = [Link]([[1, 2, 3], [4, 5, 6]])
print("Shape:", [Link])
print("Data Type:", [Link])
print("Size:", [Link])
Output:
Shape: (2, 3)
Data Type: int64
Size: 6
3. Discuss the attributes and methods on numpy arrays?
Ans: NumPy arrays, also known as ndarray (n-dimensional arrays), come with a rich
set of attributes and methods that allow for efficient data manipulation and
analysis. Here’s a comprehensive discussion on the attributes and methods available
for NumPy arrays.
Attributes of NumPy Arrays
Attributes provide information about the array and its structure:
[Link]: Returns the number of dimensions (axes) of the array.
Example:
array = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # Output: 2
[Link]: Returns a tuple representing the dimensions of the array.
Example:
print([Link]) # Output: (2, 3)

[Link]: Returns the total number of elements in the array.

Example:
print([Link]) # Output: 6

9
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

[Link]: Returns the data type of the elements in the array.


Example:
print([Link]) # Output: int64
[Link]: Returns the size (in bytes) of each element in the array.
Example:
print([Link]) # Output: 8 (for int64)
[Link]: Returns the total number of bytes consumed by the elements of the
array.
Example:
print([Link]) # Output: 48 (6 elements * 8 bytes each)
ndarray.T: Returns the transposed version of the array.
Example:
print(array.T) # Output: [[1 4] [2 5] [3 6]]
Methods of NumPy Arrays
Methods are functions that operate on arrays. Here are some key methods:
[Link](shape): Returns a new array with the same data but a new shape.
Example:
reshaped = [Link]((3, 2))
print(reshaped) # Output: [[1 2] [3 4] [5 6]]
[Link](): Returns a one-dimensional array containing all the elements of the
original array.
Example:
flat = [Link]()
print(flat) # Output: [1 2 3 4 5 6]
[Link](axis=None): Returns the sum of the array elements over the specified
axis.
Example:
print([Link]()) # Output: 21
print([Link](axis=0)) # Output: [5 7 9]
[Link](axis=None): Returns the mean of the array elements over the
specified axis.
Example:
print([Link]()) # Output: 3.5
print([Link](axis=0)) # Output: [2.5 3.5 4.5]
[Link](axis=None): Returns the standard deviation of the array elements over
the specified axis.
Example:
print([Link]()) # Output: 1.707825127659933
[Link](axis=None) and [Link](axis=None): Return the maximum and
minimum values of the array elements over the specified axis.

10
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Example:
print([Link]()) # Output: 6
print([Link]()) # Output: 1
[Link](axis=None) and [Link](axis=None): Return the indices of
the maximum and minimum values of the array elements over the specified axis.
Example:
print([Link]()) # Output: 5
print([Link]()) # Output: 0
[Link](axis=-1): Sorts the array along the specified axis.
Example:
array_to_sort = [Link]([[3, 1, 2], [6, 4, 5]])
array_to_sort.sort(axis=1)
print(array_to_sort) # Output: [[1 2 3] [4 5 6]]
[Link](): Returns a copy of the array.
Example:
array_copy = [Link]()
print(array_copy) # Output: [[1 2 3] [4 5 6]]

Unit-IV
1. Define a function? Explain how are arguments passed to a function with the help
of an example?
Ans: In Python, a function is a block of organized, reusable code that is used to
perform a single, related action. Functions provide better modularity for your
application and a high degree of code reusability.
Defining a Function
To define a function in Python, you use the def keyword, followed by the function
name, parentheses (), and a colon :. Inside the parentheses, you can specify
parameters that the function can accept. The function body contains the code to
be executed, and it is indented.
Basic Syntax
def function_name(parameters):
"""docstring (optional)"""
# Function body
# ...
return value (optional)

11
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

def: Keyword to start the function definition.


function_name: The name of the function, which should be descriptive and follow
the naming conventions (typically lowercase with words separated by
underscores).
parameters: Optional. A comma-separated list of variables that the function can
accept as input.
"""docstring""": Optional. A string that describes what the function does. This is
useful for documentation purposes.
return: Optional. Specifies the value that the function should return to the caller. If
omitted, the function returns None.
Example
Here is a simple example of a Python function that takes two numbers as
parameters and returns their sum.
def add_numbers(a, b):
"""This function adds two numbers and returns the result."""
result = a + b
return result
To call the function, you simply use its name followed by parentheses containing
the arguments:
sum_result = add_numbers(3, 5)
print(sum_result) # Output: 8
Components of a Function
Function Name: Should be descriptive and follow naming conventions (lowercase
with underscores).
def greet_user(name):
# ...
Parameters: Optional. Variables that the function accepts as inputs. They are
specified within the parentheses.
def greet_user(name):
print(f"Hello, {name}!")
Docstring: Optional. A string that describes what the function does. It is placed
right after the function definition.
def greet_user(name):
"""Prints a greeting message with the given name."""
print(f"Hello, {name}!")
Function Body: The code that executes when the function is called. It must be
indented.
def greet_user(name):
"""Prints a greeting message with the given name."""
print(f"Hello, {name}!")

12
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Return Statement: Optional. Specifies what value the function should return. If no
return statement is used, the function returns None by default.
def add_numbers(a, b):
return a + b
Calling a Function: To use a function, you call it by its name and pass the required
arguments. The function then executes its body with the provided arguments and
returns the result if specified.
def add_numbers(a, b):
"""This function adds two numbers and returns the result."""
result = a + b
return result
# Call the function
sum_result = add_numbers(3, 5)
print(sum_result) # Output: 8

How Arguments are Passed to a Function


Arguments are the actual values you pass to the function when calling it. Python uses a
mechanism known as "call by object reference" or "call by sharing." Here’s how it works:
Immutable Objects (e.g., integers, strings, tuples): When passed to a function, the function
receives a copy of the object reference. The object itself cannot be modified within the
function.
Mutable Objects (e.g., lists, dictionaries, sets): When passed to a function, the function
receives a copy of the reference to the object. The object can be modified within the
function.
Example with Immutable Object
def modify_immutable(x):
"""Function to demonstrate passing immutable objects."""
x = x + 10
print("Inside function:", x)
num = 5
modify_immutable(num)
print("Outside function:", num)
Output:
Inside function: 15
Outside function: 5
Explanation: The integer num is not changed outside the function because integers are
immutable.

13
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Example with Mutable Object


def modify_mutable(lst):
"""Function to demonstrate passing mutable objects."""
[Link](4)
print("Inside function:", lst)
numbers = [1, 2, 3]
modify_mutable(numbers)
print("Outside function:", numbers)
Output:
Inside function: [1, 2, 3, 4]
Outside function: [1, 2, 3, 4]
Explanation: The list numbers is changed both inside and outside the function because
lists are mutable.
2. List and explain the four types of arguments supported by python functions?
Ans: An argument is the value sent to the function when it is called in Python.
Arguments are often confused with parameters, and the main difference between both is
that a parameter is a variable inside the parenthesis of a function. In contrast, an
argument is a value passed to it.
Types of function arguments in python
a) Positional or Required arguments
b) Default arguments
c) Keyword arguments
d) Variable length or Arbitrary argument
Positional or Required Arguments: Positional arguments are those arguments where
values get assigned to the arguments by their position when the function is called. For
example, the 1st positional argument must be 1st when the function is called. The 2nd
positional argument needs to be 2nd when the function is called, etc.

Example: Program to subtract 2 numbers using positional arguments.

def add(a, b):


print(a - b)
add(50, 10)
# Output 40]

14
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Note: If you try to pass more arguments, you will get an error.

def add(a, b):


print(a - b)
add(105, 561, 4)
Output
TypeError: add() takes 2 positional arguments but 3 were given

Default arguments:
 In a function, arguments can have default values. We assign default values to the
argument using the ‘=’ (assignment) operator at the time of function definition.
 You can define a function with any number of default arguments.
 The default value of an argument will be used inside a function if we do not pass a
value to that argument at the time of the function call.
 Due to this, the default arguments become optional during the function call.
 It overrides the default value if we provide a value to the default arguments during
function calls.
 Default arguments should follow non-default arguments.
Example:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
Output
Sum: 5
Sum: 10
Sum: 15
Keyword arguments or Named arguments:
 Usually, at the time of the function call, values get assigned to the arguments according
to their position.
 So we must pass values in the same sequence defined in a function definition. We can
alter this behavior using a keyword argument.
 Keyword arguments are those arguments where values get assigned to the arguments
by their keyword (name) when the function is called.
 It is preceded by the variable name and an (=) assignment operator. The Keyword
Argument is also called a named argument.

15
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

 Also, you can change the sequence of keyword arguments by using their name in
function calls.
 Python allows functions to be called using keyword arguments. But all the keyword
arguments should match the parameters in the function definition.
 When we call functions in this way, the order (position) of the arguments can be
changed.
Example 1:
def sum(a,b):
print(a+b)
sum(b=4,a=10)

OUTPUT:
14
Example 2:
def sum(a,c):
print(a+c)
sum(b=4,a=10)

OUTPUT:
TypeError: sum() got an unexpected keyword argument 'b'

Variable-length arguments or Arbitrary Arguments:


 Sometimes, we do not know in advance the number of arguments that will be passed
into a function.
 To handle this kind of situation, we can use arbitrary arguments in Python. Arbitrary
arguments in Python enable functions to accept an unlimited number of arguments.
 This allows for flexibility when creating functions that require an unknown number of
arguments.
Types of Arbitrary Arguments:
1. Arbitrary or variable-length positional arguments (*args)
2. Arbitrary or variable-length keyword arguments (**kwargs)
The *args and **kwargs allow you to pass multiple positional arguments or keyword
arguments to a function.

Arbitrary Positional Arguments in Python (*args):


 For arbitrary positional argument, an asterisk (*) is placed before a parameter in
function definition which can hold non-keyword variable-length arguments.
 These arguments will be wrapped up in a tuple. Before the variable number of
arguments, zero or more normal arguments may occur.

16
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Example:
def var(*n):
print(n)
var(10)
var(10,20)
var(10,20,30)
var()
Output:
(10,)
(10, 20)
(10, 20, 30)
()

Arbitrary Keyword Arguments in Python (**kwargs):


 The **kwargs allow you to pass multiple keyword arguments to a function. Use the
**kwargs if you want to handle named arguments in a function.
 Use the unpacking operator(**) to define variable-length keyword arguments.
 Keyword arguments passed to a kwargs are accessed using key-value pair (same as
accessing a dictionary in Python).
Example:
def var(**n):

print(n)
var(name="Raju",course="[Link]",college="MRCET")
var()
OUTPUT:
{'name': 'Raju', 'course': '[Link]', 'college': 'MRCET'}
{}
Important points to remember about function argument
Point 1: Default arguments should follow non-default arguments
Example:
def get_student(name, grade='Five', age):
print(name, age, grade)
# output: SyntaxError: non-default argument follows default argument

Point : Default arguments must follow the default argument in a function definition
Default arguments must follow the default argument. For example, When you use the
default argument in a definition, all the arguments to their right must also have default
values. Otherwise, you’ll get an error.
Example:

17
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

def student(name, grade="Five", age):


print('Student Details:', name, grade, age)

student('Jon', 'Six', 12)


# Output: SyntaxError: non-default argument follows default argument
Point 2: keyword arguments should follow positional arguments only.
we can mix positional arguments with keyword arguments during a function call. But, a
keyword argument must always be after a non-keyword argument (positional argument).
Else, you’ll get an error. I.e., avoid using keyword argument before positional argument.

Example:
def get_student(name, age, grade):
print(name, age, grade)
get_student(name='Jessa', 12, 'Six')

# Output: SyntaxError: positional argument follows keyword argument


Point 3: The order of keyword arguments is not important, but All the keyword arguments
passed must match one of the arguments accepted by the function.
Example:
def get_student(name, age, grade):
print(name, age, grade)
get_student(grade='Six', name='Jessa', age=12)
# Output: Jessa 12 Six
get_student(name='Jessa', age=12, standard='Six')
# Output: TypeError: get_student() got an unexpected keyword argument 'standard'
Point 4: No argument should receive a value more than once
Example:
def student(name, age, grade):
print('Student Details:', name, grade, age)
student(name='Jon', age=12, grade='Six', age=12)
# Output: SyntaxError: keyword argument repeated

3. What are fruitful functions? Discuss with syntax and example?


Ans: Fruitful functions are those that return a value when called. They are
fundamental in programming because they allow you to compute a result that can
be used elsewhere in your code. Here's a discussion of fruitful functions with
syntax and an example.
Syntax
def function_name(parameters):
# Function body
return value

18
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

In Python, the syntax for defining a fruitful function includes the def keyword, the
function name, parentheses (which may include parameters), and a return
statement. The return statement is what makes the function "fruitful."
Example
Here's an example of a simple fruitful function that calculates the square of a
number:
def square(x):
result = x * x
return result
num = 5
squared_value = square(num)
print(squared_value)

# Output: 25
Explanation:
Function Definition: def square(x): defines a function named square that takes one
parameter x.
Computation: result = x * x calculates the square of x and stores it in result.
Return Statement: return result returns the computed value to the caller.
Function Call: squared_value = square(num) calls the square function with num as
the argument and stores the returned value in squared_value.
Output: print(squared_value) prints the result, which is 25.
Importance :Fruitful functions are essential because they:
Enable modularity: Functions can be reused in different parts of the program.
Improve readability: Breaking down complex calculations into simpler, named
functions makes the code easier to understand.
Facilitate testing: Functions can be tested individually to ensure they produce the
correct results.
4. Explain about local and global scope of variables in python with an example?
Ans: A variable's scope is basically the lifespan of that variable. Based on the scope,
we can classify Python variables into three types:
1. Local Variables
2. Global Variables
3. Nonlocal Variables
Local Variables: When we declare variables inside a function, these variables will
have a local scope (within the function). We cannot access them outside the
function.
Example:
def fn():
a=10
print(a)

19
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

fn()
print("local=",a)

Output:
10
NameError: name 'a' is not defined
global Variables: In Python, a variable declared outside of the function or in global scope
is known as a global variable. This means that a global variable can be accessed inside or
outside of the function.

Example:

a=10
def fn():
print("Inside function=",a)
fn()
print("Outside function=",a)

Output:
Inside function= 10
Outside function= 10

global Keyword: If you need to create a global variable, but are stuck in the local scope,
you can use the global keyword. The global keyword makes the variable global.

Example:

def fn():
global a
a=10
print("Inside function=",a)
fn()
print("Outside function=",a)

Output:
Inside function= 10
Outside function= 10

Nonlocal Variables: In python, nonlocal variables refer to all those variables that are
declared within nested functions. In Python, nonlocal variables are used in nested
functions whose local scope is not defined. This means that the variable can be neither in
the local nor the global scope. We use the nonlocal keyword to create nonlocal variables.
If we change the value of a nonlocal variable, the changes appear in the local variable.

20
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Example:

def myfunc1():
x = 10 # Local variable
def myfunc2():
nonlocal x
x = 20
myfunc2()
return x
print(myfunc1())
Output:

20

Difference Between Local and Global Variables: Local Variables vs Global Variables

Parameter Local Variables Global Variables


Defined inside a function or Defined outside of all functions or
Definition
block. blocks.
Accessible only within the Accessible throughout the entire
Scope
function/block where it’s defined. program.
Exists only during the function’s Remains in memory for the duration
Lifetime
execution. of the program.
Cannot be accessed outside its Can be accessed and modified by any
Accessibility
function. function in the program.
Keyword for Use the global keyword to modify it
No special keyword is required.
Modification inside a function.
Stored in the data segment of
Memory Storage Stored in the stack.
memory.
Risk of Unintended Low, as it’s confined to its
Higher, as any function can modify it.
Modification function.

5. Compare and contrast an anonymous function and a regular function?


Ans: Python lambda functions and regular functions differ in syntax and usage. Here are
the key differences:
Definition and syntax:
Lambda Functions: Lambda functions are defined using the "lambda" keyword, followed
by a list of arguments and a single expression.
Syntax:
lambda parameters: expression

21
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Example :
lambda_function_result = lambda x, y: x * y

Regular Functions: Regular functions are defined using the "def" keyword, followed by the
function name, a list of parameters in parentheses, and a block of code indented below.
Syntax:
def function_name(parameters):
body
Example:
def regular_function(x, y):
return x * y
Function Name:
Lambda Functions: Lambda functions are anonymous functions, which means they have
no name. As a result, they can be passed as arguments to other functions or used directly
in expressions.
Regular Functions: Regular functions have a name assigned to them, enabling them to be
called and reused by that name.
Number of lines:
Lambda Functions: Lambda functions can only contain a single expression and cannot
contain multiple lines of code. They are designed for short and simple operations.
Regular Functions: Regular functions can contain several lines of code and can be more
complex, allowing for better code organization and readability.
Return Statement:
Lambda Functions: Lambda functions return the result of evaluating an expression. There
is no need to use a return statement explicitly.
Regular Functions: Regular functions return a value explicitly using a return statement. If
no return statement is used, the function returns None.
Usage:
Lambda Functions: Lambda functions are commonly used as anonymous functions for
one-time or short operations. They are often used in functional programming constructs
like map, filter, and sorted.
Regular Functions: These are more substantial, reusable code blocks that can be called
multiple times in the program.
6. Demonstrate the use of map, filter and reduce functions with suitable examples?

Ans:

 Python's map(), filter(), and reduce() functions add a touch of functional


programming to the language.
 All three of these are convenience functions that can be replaced with List
Comprehensions or loops but offer a more elegant and concise solution to some
problems.

22
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

 map(), filter(), and reduce() all work in the same way. These functions accept a
function and a sequence of elements and return the result of applying the received
function to each element in the sequence.

map() function : The map() function allows you to iterate over each item in an iterable.
map(), on the other hand, operates independently on each item rather than producing a
single result. Finally, the map() function can be used to perform mathematical operations
on two or more lists. It can even be used to manipulate any type of array.
Syntax
map(function, iterable)
Parameters
function − The function to be used in the code.
iterable − This is the value that is iterated in the code.
Example :
a=list(map(int,input().split()))
b=list(map(lambda x:x+2,a))
print(b)
OUTPUT:
10 20 30 40
[12,22,32,42]
filter() function : The filter() function creates a new iterator that filters elements from a
previously created one (like a list, tuple, or dictionary).The filter() function checks whether
or not the given condition is present in the sequence and then prints the result.
Syntax
filter(function, iterable)
Parameters
function − The function to be used in the code.
iterable − This is the value that is iterated in the code.
Example :
a=list(map(int,input().split()))
print("List a= ",a)
b=list(filter(lambda x:(x<0),a))
print(b)
OUTPUT:
10 -2 -3 45 -9 67 78 -90
List a= [10, -2, -3, 45, -9, 67, 78, -90]
[-2, -3, -9, -90]
reduce() : In Python, the reduce() function iterates through each item in a list or other
iterable data type, returning a single value. It's in the functools library. This is more
efficient than looping. The reduce() function belongs to the functools module.

23
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Syntax
reduce(function, iterable)
Parameters
function − The function to be used in the code.
iterable − This is the value that is iterated in the code.
Example:
from functools import reduce
reduce(lambda a,b: a+b, [23,21,45,98])

OUTPUT:
187
Unit-V
1. Define a file and explain the two categories of files?
Ans:
 Mostly, in programming languages, all the values or data are stored in some
variables which are volatile in nature.
 Because data will be stored into those variables during run-time only and will be
lost once the program execution is completed.
 Hence it is better to save these data permanently using files.
 If you are working in a large software application where they process a large
number of data, then we cannot expect those data to be stored in a variable as the
variables are volatile in nature.
 Hence when are you about to handle such situations, the role of files will come
into the picture.
 A file is a resource to store data. As part of the programming requirement, we
may have to store our data permanently for future purpose.
 For this requirement we should go for files. Files are very common permanent
storage areas to store our data.
Types Of File in Python
There are two types of files in Python and each of them are explained below in
detail with examples for your easy understanding.
They are:
Binary file
Text file
Binary Files: Binary files, on the other hand, contain data in a format that is not
directly human-readable. These files store information in binary form, which is a
sequence of bytes that can represent any type of data, including text, images,
audio, and executable programs.
Example:
Document files: .pdf, .doc, .xls etc.

24
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Image files: .png, .jpg, .gif, .bmp etc.


Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
Text Files: Text files are composed of sequences of characters, typically encoded in
standard character sets such as ASCII or UTF-8. They are human-readable and can
be easily created and edited using simple text editors.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
2. List out different types of file modes in python?
Ans: Most importantly there are 4 types of operations that can be handled by
Python on files:
Open
Read
Write
Close
Other operations include:
Rename
Delete
Python Create and Open a File
Python has an in-built function called open() to open a file.
It takes a minimum of one argument as mentioned in the below syntax. The open
method returns a file object which is used to access the write, read and other in-
built methods.
Syntax:
file_object = open(file_name, mode)
Here, file_name is the name of the file or the location of the file that you want to
open, and file_name should have the file extension included as well. Which means
in [Link] – the term test is the name of the file and .txt is the extension of the file.
The mode in the open function syntax will tell Python as what operation you want
to do on a file.

SNo Access Description


mode

25
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

1 r r means to read. So, it opens a file for read-only operation. The file
pointer exists at the beginning. The file is by default open in this
mode if no access mode is passed.

2 rb It opens the file to read-only in binary format. The file pointer exists at
the beginning of the file.

3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.

4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.

5 w It opens the file to write only. It overwrites the file if previously exists
or creates a new one if no file exists with the same name. The file
pointer exists at the beginning of the file.

6 wb It opens the file to write only in binary format. It overwrites the file if it
exists previously or creates a new one if no file exists. The file pointer
exists at the beginning of the file.

7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites the previous file if one exists whereas r+
doesn't overwrite the previously written file. It creates a new file if no
file exists. The file pointer exists at the beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.

9 a It opens the file in the append mode. The file pointer exists at the end
of the previously written file if exists any. It creates a new file if no file
exists with the same name.

10 ab It opens the file in the append mode in binary format. The pointer
exists at the end of the previously written file. It creates a new file in
binary format if no file exists with the same name.

11 a+ It opens a file to append and read both. The file pointer remains at
the end of the file if a file exists. It creates a new file if no file exists
with the same name.

12 ab+ It opens a file to append and read both in binary format. The file
pointer remains at the end of the file.

26
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

3. Show with an appropriate example, how read and write operations are performed
on a file?
Ans: Reading from and writing to files are fundamental operations in programming. Here,
we'll illustrate these operations using Python, which is widely used for such tasks due to
its simplicity and readability.
Example: Reading from and Writing to a File in Python
We'll demonstrate how to perform read and write operations on a text file. The example
includes creating a file, writing data to it, and then reading the data back from the file.
Writing to a File
First, let's create a file and write some data to it.
# Open a file in write mode. If the file doesn't exist, it will be created.
with open('[Link]', 'w') as file:
# Write some lines of text to the file
[Link]("Hello, World!\n")
[Link]("This is an example of file write operation.\n")
[Link]("File operations are fundamental in programming.\n")
In this example:
The open function opens the file [Link] in write mode ('w'). If the file doesn't exist, it
is created.
The with statement ensures that the file is properly closed after the block of code is
executed.
The write method writes strings to the file. Each write call adds text to the file. The \n
characters create new lines.
Reading from a File
Next, let's read the data back from the file we just wrote to.
# Open the file in read mode
with open('[Link]', 'r') as file:
# Read all lines from the file
lines = [Link]()
# Print each line
for line in lines:
print(line, end='')
In this example:
The open function opens the file [Link] in read mode ('r').
The readlines method reads all the lines of the file into a list where each element is a line
from the file.
We iterate through the list and print each line. The end='' in the print function avoids
adding extra newlines, as the lines already contain newline characters.
Output
When you run the above code, the output will be:
Hello, World!

27
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

This is an example of file write operation.


File operations are fundamental in programming.
Explanation
Writing to a File:
The open('[Link]', 'w') statement opens the file in write mode.
The [Link] methods add the specified strings to the file.
Each string is written in sequence, with \n ensuring each new string appears on a new line.
Reading from a File:
The open('[Link]', 'r') statement opens the file in read mode.
The [Link]() method reads all lines from the file and stores them in the lines list.
The for line in lines loop iterates through each line, printing them exactly as they are
stored in the file.
4. What is an exception? Demonstrate with syntax and example how exceptions can be
handled?
Ans:
 An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
 In general, when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an error.
 When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

Understanding Exceptions and Syntax Errors


Syntax errors occur when the parser detects an incorrect statement. Observe the
following example:
>>> print(0 / 0))
File "<stdin>", line 1
print(0 / 0))
^
SyntaxError: unmatched ')'
The arrow indicates where the parser ran into the syntax error. Additionally, the error
message gives you a hint about what went wrong. In this example, there was one
bracket too many. Remove it and run your code again:
>>> print(0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
This time, you ran into an exception error. This type of error occurs whenever syntactically
correct Python code results in an error. The last line of the message indicates what type of
exception error you ran into.

28
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

Instead of just writing exception error, Python details what type of exception error it
encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in
exceptions as well as the possibility to create user-defined exceptions.
Handling an Exception in Python
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include an
except: statement, followed by a block of code which handles the problem as elegantly as
possible.
Syntax
Here is the simple syntax of try...except...else blocks −
try:
# Code that might raise an exception
except SomeException as e:
# Code that runs if the exception occurs
else:
# Code that runs if no exception occurs
finally:
# Code that always runs, whether an exception occurred or not
Here are few important points about the above-mentioned syntax –
3. A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions.
4. You can also provide a generic except clause, which handles any exception.
5. After the except clause(s), you can include an else clause. The code in the else block
executes if the code in the try: block does not raise an exception.
6. The else block is a good place for code that does not need the try: block's protection.
Example
Let's demonstrate exception handling with a practical example. We will handle a division
by zero exception.
def divide_numbers(a, b):
try:
# Attempt to divide the numbers
result = a / b
except ZeroDivisionError as e:
# Handle division by zero exception
print("Error: Cannot divide by zero!")
print("Exception details:", e)
else:
# If no exception occurs
print("The result is:", result)
finally:
# Code that will always execute

29
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

print("Execution of divide_numbers is complete.")

# Test cases
divide_numbers(10, 2) # Normal case
divide_numbers(10, 0) # Division by zero case
Output When the example is executed, the output will be:
The result is: 5.0
Execution of divide_numbers is complete.
Error: Cannot divide by zero!
Exception details: division by zero
Execution of divide_numbers is complete.
5. Explain any 6 exceptions that could occur in code with suitable examples?
Ans:

Here is the list of default Python exceptions with descriptions:

1. AssertionError: raised when the assert statement fails.


2. EOFError: raised when the input() function meets the end-of-file condition.
3. AttributeError: raised when the attribute assignment or reference fails.
4. TabError: raised when the indentations consist of inconsistent tabs or spaces.
5. ImportError: raised when importing the module fails.
6. IndexError: occurs when the index of a sequence is out of range
7. KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or
Delete).
8. RuntimeError: occurs when an error does not fall into any category.
9. NameError: raised when a variable is not found in the local or global scope.
10. MemoryError: raised when programs run out of memory.
11. ValueError: occurs when the operation or function receives an argument with the
right type but the wrong value.
12. ZeroDivisionError: raised when you divide a value or variable with zero.
13. SyntaxError: raised by the parser when the Python syntax is wrong.
14. IndentationError: occurs when there is a wrong indentation.
15. SystemError: raised when the interpreter detects an internal error.
Common Python Exceptions and Examples

ZeroDivisionError: This exception is raised when a division or modulo operation is


performed with zero as the divisor.
30
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero!", e)

FileNotFoundError: This exception is raised when an attempt to open a file fails


because the file cannot be found.

try:

with open('nonexistent_file.txt', 'r') as file:

content = [Link]()

except FileNotFoundError as e:

print("File not found!", e)

TypeError: This exception is raised when an operation or function is applied to an


object of inappropriate type.

try:
result = 'string' + 10
except TypeError as e:
print("Type mismatch!", e)
ValueError: This exception is raised when a function receives an argument of the
correct type but an inappropriate value.

try:

number = int("not_a_number")

except ValueError as e:

print("Invalid value!", e)

IndexError: This exception is raised when an attempt is made to access an element from
a list or tuple using an index that is out of range.

try:
my_list = [1, 2, 3]
element = my_list[5]
except IndexError as e:

31
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22

print("Index out of range!", e)


KeyError: This exception is raised when a dictionary is accessed with a key that does
not exist.

try:

my_dict = {'a': 1, 'b': 2}

value = my_dict['c']

except KeyError as e:

print("Key not found!", e)

32
MRCET [Link], [Link]., CSE(ET)

You might also like