Python NumPy and Functions Guide
Python NumPy and Functions Guide
1
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22
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
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
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.
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)
Example:
print([Link]) # Output: 6
9
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22
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
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
13
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22
14
MRCET [Link], [Link]., CSE(ET)
PYTHON PROGRAMMING R22
Note: If you try to pass more arguments, you will get an error.
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'
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)
()
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
Example:
def get_student(name, age, grade):
print(name, age, grade)
get_student(name='Jessa', 12, 'Six')
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
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:
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
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
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
# 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:
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero!", e)
try:
content = [Link]()
except FileNotFoundError as e:
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
try:
value = my_dict['c']
except KeyError as e:
32
MRCET [Link], [Link]., CSE(ET)