2 Lab Manual
2 Lab Manual
LAB MANUAL
Assistant Professor
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 1:
Title/Problem Statement:
Create variables of different data types (integer, float, string, Boolean). Perform basic
operations on them and print the results along with their types using the type () function.
Description:
In this exercise, you will create variables of different data types: integer, float, string, and
Boolean. You will perform basic operations such as addition, concatenation, and logical
operations on these variables. After performing the operations, you will print the results
along with the data type of each result using the `type()` function. This exercise helps in
understanding how different data types behave and how to work with them in Python.
Theory:
In programming, variables can hold different types of data, such as integers, floats, strings,
and Boolean values. Each data type serves a specific purpose:
1. Integer (`int`): Represents whole numbers, like `5` or `-3`. Operations like addition or
subtraction can be performed on integers.
2. Float (`float`): Represents decimal numbers, like `3.14` or `-0.001`. Operations such as
multiplication or division are commonly used with floats.
3. String (`str`): Represents sequences of characters, like `"Hello"` or `"123"`. Strings can be
concatenated or sliced to extract parts of the text.
4. Boolean (`bool`): Represents truth values, `True` or `False`. Boolean values are used in
logical operations and conditions.
To explore these data types, you can create variables for each type and perform basic
operations on them. For instance, add two integers, concatenate two strings, or check the
result of a Boolean expression. After performing these operations, you can use the `type()`
function to print the type of each result. This function helps identify the data type of the
variable and ensures you are performing operations appropriate for that type. For example,
`type(5)` will return `<class 'int'>`, and `type("Hello")` will return `<class 'str'>`.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
3. Printing Results:
o Each result is printed along with its type using the type() function.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
This program demonstrates how to handle different data types, perform basic operations,
and inspect the results in Python.
6
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Conclusion:
In conclusion, creating and manipulating variables of different data types—integer, float,
string, and Boolean—demonstrates the versatility and dynamic nature of Python. By
performing basic operations such as arithmetic calculations, string concatenation, and
logical comparisons, you can see how different data types interact and behave. Printing the
results along with their types using the `type()` function provides a clear understanding of
the data types at each step, ensuring clarity and correctness in data handling. This
foundational knowledge is crucial for efficient programming and data processing in Python.
7
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 2:
Title/Problem Statement:
Create an array, perform various operations such as insertion, deletion, searching for
elements, and iterating through the array. Compare the performance of arrays with lists for
certain operations.
Description:
In this exercise, you will create an array and perform various operations including insertion,
deletion, searching for elements, and iterating through the array. You will then compare the
performance of these operations when using arrays versus lists. This comparison helps in
understanding the efficiency and suitability of arrays and lists for different types of
operations in programming.
Theory:
In programming, an array is a collection of elements stored in contiguous memory
locations, where each element can be accessed using an index. Arrays are useful for storing
and managing a fixed-size sequence of elements of the same type.
Operations on Arrays:
1. Insertion: Adding an element to an array usually requires shifting other elements to make
room. This operation can be costly in terms of performance, especially for large arrays.
2. Deletion: Removing an element involves shifting elements to fill the gap left by the
removed element. Like insertion, this can be inefficient for large arrays.
3. Searching: Finding an element in an array requires checking each element sequentially
(linear search) unless the array is sorted, in which case more efficient algorithms like binary
search can be used.
4. Iteration: Traversing through an array to access or modify its elements is straightforward
and efficient, as each element can be accessed directly using its index.
8
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Arrays are generally preferred for performance-critical applications where the size is known
and fixed, while lists offer more flexibility and ease of use for dynamic collections of
elements.
# Insertion
arr.insert(2, 6) # Insert 6 at index
2 print("Array after insertion:",
arr)
# Deletion
arr.remove(4) # Remove the first occurrence of 4
print("Array after deletion:", arr)
# Searching
index = arr.index(3) # Find the index of the first occurrence of 3
print("Index of 3 in the array:", index)
# Iteration
print("Iterating through the
array:") for element in arr:
print(element, end=" ")
print()
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
Array Creation: An array of integers is created using the array module.
Insertion: An element is inserted at a specified index.
Deletion: An element is removed from the array.
Searching: The index of a specific element is found.
Iteration: The program iterates through the array and prints each element.
Performance Comparison: The timeit module is used to compare the performance of array
and list operations, including insertion, deletion, and searching. The results are printed to
show the time taken for each operation.
Conclusion:
In conclusion, working with arrays involves performing various fundamental operations
such as insertion, deletion, searching, and iteration. Arrays are fixed-size structures that
offer efficient indexing and quick access to elements, making them suitable for tasks
requiring constant-time access. However, operations like insertion and deletion can be
costly, as they may require shifting elements or resizing the array.
On the other hand, lists in Python, which are dynamic arrays, provide more flexibility by
allowing dynamic resizing and simpler syntax for common operations. They handle
insertions and deletions more gracefully compared to fixed-size arrays, though this
flexibility comes with some performance trade-offs.
Comparing the performance of arrays and lists reveals that while arrays can be more
efficient in scenarios with fixed-size data and constant-time access requirements, lists offer
greater ease of use and adaptability for dynamically changing datasets. Understanding
these differences helps in selecting the appropriate data structure based on the specific
needs of the application, balancing between performance and flexibility.
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 3:
Title/Problem Statement:
Write a program to read data from a text file, process the data (such as counting words,
lines, and characters), and write the processed data to a new file. Handle potential
exceptions that may occur during file operations.
Description:
In this task, you will write a program to read data from a text file, process the data by
counting the number of words, lines, and characters, and then write the processed data to
a new file. The program should include error handling to manage potential exceptions that
may occur during file operations, such as file not found or read/write errors. This exercise
helps in mastering file I/O operations and exception handling in Python.
Theory:
To write a program that reads data from a text file and processes it, follow these steps:
1. Reading Data: Open the text file in read mode using Python's built-in `open()` function.
Use methods like `.read()`, `.readline()`, or `.readlines()` to retrieve the file's content.
2. Processing Data: Count the number of lines, words, and characters in the file. For
counting lines, split the content by newline characters. For words, split the content by
spaces. Count characters directly from the content.
3. Writing Processed Data: Open a new file in write mode using `open()` with `'w'` mode.
Write the processed results (like counts) to this new file using the `.write()` method.
4. Exception Handling: Include error handling using `try` and `except` blocks to manage
exceptions that might occur during file operations, such as `FileNotFoundError` if the input
file doesn't exist or `IOError` for issues during reading or writing.
This program ensures proper handling of file data and provides robust error management,
making it resilient to common file operation issues.
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
except FileNotFoundError:
print(f"Error: The file {input_file} was not found.")
except IOError:
print(f"Error: An IOError occurred while handling the file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
# Example usage
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
1. Function Definition: process_file takes two parameters: input_file (the name of the
file to read) and output_file (the name of the file to write).
2. Reading the Input File:
o Open the input file in read mode.
o Initialize counters for lines, words, and characters.
o Loop through each line in the file, updating the counters accordingly.
3. Writing to the Output File:
o Open the output file in write mode.
o Write the counts of lines, words, and characters to the output file.
4. Exception Handling:
o FileNotFoundError: Catches errors if the input file does not exist.
o IOError: Catches input/output errors.
o Exception: Catches any other unexpected errors.
5. Example Usage: Replace 'input.txt' and 'output.txt' with your actual file names to test
the program.
This program ensures that it handles common file-related exceptions and provides feedback
if something goes wrong during file operations.
Conclusion:
In conclusion, writing a program to read data from a text file, process it, and then write the
results to a new file is a practical exercise in file handling and data processing. This task
involves:
1. Reading Data: Opening and reading the contents of the source text file using appropriate
file handling methods.
2. Processing Data: Performing operations such as counting the number of words, lines, and
characters to analyze the content.
3. Writing Data: Saving the processed results to a new file to preserve the output and
facilitate further use or review.
4. Exception Handling: Implementing error handling to manage potential issues such as file
not found, permission errors, or I/O errors, ensuring that the program runs smoothly and
provides informative error messages when problems occur.
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Overall, this process demonstrates key programming skills related to file manipulation, data
analysis, and robust error handling, which are essential for effective software development
and data management.
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 4:
Title/Problem Statement:
Create a program that raises and handles various types of exceptions (such as Value Error,
Type Error, and FileNotFoundError). Define and raise custom exceptions to handle specific
error conditions in your program
Description:
In this exercise, you will create a program that demonstrates how to raise and handle
various built-in exceptions in Python, such as `ValueError`, `TypeError`, and
`FileNotFoundError`. You will also define custom exceptions tailored to specific error
conditions within your program. This exercise will enhance your understanding of exception
handling mechanisms in Python and how to create robust programs by managing errors
effectively.
Theory:
In Python, exceptions are used to handle errors that occur during program execution. When
an error occurs, Python raises an exception, which can be caught and handled using try and
except blocks to prevent the program from crashing.
1. ValueError: Raised when an operation receives an argument of the right type but
inappropriate value (e.g., converting a non-numeric string to an integer).
2. TypeError: Raised when an operation is applied to an object of inappropriate type
(e.g., adding a string to an integer).
3. FileNotFoundError: Raised when trying to open a file that does not exist.
Handling Exceptions: Use try to execute code that might raise an exception and except to
catch and handle specific exceptions. You can handle multiple exceptions by defining
multiple except blocks or a single block with multiple exception types.
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
class CustomTypeError(Exception):
def init (self, message):
self.message = message
super(). init (self.message)
# Example of handling
TypeError if not
isinstance(value, int):
raise TypeError("Value must be an integer.")
# Example usage
print("Testing with a negative
value:") exception_handling_demo(-
5)
print("\nTesting with a valid value that does not cause any exceptions:")
exception_handling_demo(3)
Explanation:
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
This program covers various aspects of exception handling, including built-in and custom
exceptions, to demonstrate robust error handling in Python.
Conclusion:
In conclusion, creating a program that raises and handles various types of exceptions is
crucial for building robust and reliable software. By understanding and implementing
exception handling mechanisms, such as `ValueError`, `TypeError`, and `FileNotFoundError`,
you can gracefully manage common runtime errors and ensure that your program can
recover or provide meaningful feedback to users.
Defining and raising custom exceptions allows you to handle specific error conditions
tailored to your application's needs, offering more control over error management. This
approach helps in debugging, maintaining code, and improving user experience by
providing clearer error messages and handling unexpected situations effectively. Overall,
mastering exception handling and custom exceptions enhances the reliability and resilience
of your program.
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 5:
Title/Problem Statement:
Write a program in Python to demonstrate the concept of a Constructor
Description:
In this task, you will write a Python program to demonstrate the concept of a constructor in
object-oriented programming. You will define a class with an ` init ` method, which
serves as the constructor to initialize the object's attributes. The program will create
instances of the class, showing how constructors are used to set up initial values for
objects. This exercise illustrates how constructors ensure that objects are created with a
valid initial state.
Theory:
def display_info(self):
# Method to display the person's information
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
print(f"Name: {self.name}")
print(f"Age: {self.age}")
Conclusion:
In conclusion, demonstrating the concept of a constructor in Python reveals its crucial role
in object-oriented programming. A constructor, defined by the ` init ` method, is used to
initialize an object's attributes when an instance of a class is created. This ensures that
objects are set up with default or initial values, allowing for consistent and predictable
behavior. By understanding and implementing constructors, you can effectively manage
object state and streamline object creation, laying a strong foundation for more complex
programming and design patterns.
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 6:
Title/Problem Statement:
Write a program in Python to demonstrate the concept of Interface
Description:
In this exercise, you will write a Python program to demonstrate the concept of an interface
using abstract base classes (ABCs) from the `abc` module. Define an abstract class with one
or more abstract methods that must be implemented by any subclass. Then, create
concrete subclasses that provide specific implementations of these abstract methods. This
exercise helps in understanding how to define and enforce interfaces in Python, promoting
code consistency and reusability.
Theory:
In Python, the concept of an "interface" can be demonstrated using abstract base classes
(ABCs) from the abc module. An interface in programming defines a contract or a set of
methods that a class must implement, without providing the method implementations.
1. Abstract Base Classes (ABCs): In Python, you can create an abstract base class to
serve as an interface. This class can define abstract methods that must be
implemented by any subclass. Use the abc module for this purpose.
2. Creating an Interface:
o Import the ABC and abstractmethod classes from the abc module.
o Define a class that inherits from ABC.
o Use the @abstractmethod decorator to declare methods that subclasses must
implement.
3. Implementing the Interface:
o Create a subclass of the abstract base class.
o Provide concrete implementations for all the abstract methods defined in the
base class.
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
@abstractmethod
def area(self):
"""Method to calculate the area of the shape."""
pass
@abstractmethod
def perimeter(self):
"""Method to calculate the perimeter of the shape."""
pass
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def area(self):
import math
return math.pi * self.radius ** 2
def perimeter(self):
import math
return 2 * math.pi * self.radius
print("Rectangle Information:")
print_shape_info(rectangle)
print("\nCircle Information:")
print_shape_info(circle)
Explanation:
This example illustrates how to define and use interfaces in Python, ensuring that classes
adhere to a specific contract, thereby promoting consistency and modularity in the code.
Conclusion:
In conclusion, writing a program in Python to demonstrate the concept of an interface
underscores its importance in defining a contract for classes. Although Python does not
have formal interfaces like some other languages, abstract base classes (ABCs) from the
`abc` module can be used to achieve similar functionality. By creating an abstract class with
abstract methods, you ensure that derived classes implement these methods, enforcing a
consistent interface across different implementations. This approach enhances code
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
organization, promotes adherence to design principles, and improves the scalability and
maintainability of the software.
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 7:
Title/Problem Statement:
Write a program in Python to demonstrate the concept of Inheritance.
Description:
In this exercise, you will write a Python program to demonstrate the concept of inheritance,
where a new class (child class) is derived from an existing class (parent class). The child class
inherits attributes and methods from the parent class, allowing for code reuse and
extension. You will create a base class and a derived class, showcasing how the derived
class can access and override the properties and methods of the base class. This exercise
illustrates the fundamental object-oriented programming concept of inheritance.
Theory:
1. Define a Base Class: Create a class Animal with basic attributes and methods that are
common to all animals, such as a method to make a sound.
2. Create Derived Classes: Define subclasses Dog and Cat that inherit from Animal.
These subclasses can have their own specific methods or override existing ones from
the Animal class.
3. Instantiate and Use: Instantiate objects of the Dog and Cat classes and call their
methods to see how they inherit and use functionality from the Animal class.
def speak(self):
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
# Derived class
class Dog(Animal):
def init (self, name, breed):
super(). init (name) # Call the constructor of the base class
self.breed = breed
def speak(self):
return "Woof!"
def speak(self):
return "Meow!"
# Demonstration
def main():
# Create instances of Dog and Cat
dog = Dog(name="Buddy", breed="Golden Retriever")
cat = Cat(name="Whiskers", color="Black")
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
This example illustrates how inheritance enables the creation of specialized classes while
reusing common functionality defined in a base class.
Conclusion:
In conclusion, writing a Python program to demonstrate inheritance showcases how this
fundamental object-oriented programming concept enables code reuse and establishes a
hierarchical relationship between classes. Inheritance allows a new class (subclass) to
inherit attributes and methods from an existing class (superclass), promoting modularity
and reducing redundancy. By extending the functionality of a superclass, subclasses can
override or add new features, leading to more organized and maintainable code. This
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
approach not only simplifies the development process but also enhances the ability to
model complex systems in a scalable manner.
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 8:
Title/Problem Statement:
Write a program to install NumPy and create arrays using lists and built-in functions. Display
the created arrays and their attributes
Description:
In this exercise, you will write a program to install the NumPy library and use it to create
arrays from lists and NumPy's built-in functions. You will display the created arrays along
with their attributes such as shape, size, and data type. This exercise demonstrates how to
set up and use NumPy for array manipulation and exploring array properties in Python.
Theory:
To work with numerical data efficiently in Python, you'll use the NumPy library, which
provides support for large, multi-dimensional arrays and matrices. Here’s a simplified guide:
1. Install NumPy: First, you need to install NumPy. This can be done using the package
manager pip with the command `pip install numpy`.
2. Import NumPy: Once installed, import the library into your Python script with `import
numpy as np`.
3. Create Arrays from Lists: You can create NumPy arrays from Python lists using the
`np.array()` function. For example, `np.array([1, 2, 3])` creates a 1-dimensional array with
the elements 1, 2, and 3.
4. Create Arrays Using Built-in Functions: NumPy also offers functions to create arrays with
specific properties, such as `np.zeros((2, 3))` to create a 2x3 array filled with zeros or
`np.arange(0, 10, 2)` to create an array of numbers from 0 to 10 with a step of 2.
5. Display Arrays and Attributes: Print the arrays to view their contents. You can also
explore attributes like `shape`, `dtype`, and `size`:
- `shape` gives the dimensions of the array.
- `dtype` indicates the data type of the elements.
- `size` shows the total number of elements in the array.
This process helps you efficiently handle and analyze numerical data using NumPy’s
powerful array operations.
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
print("Array of zeros:")
print(numpy_array_zeros)
print("Shape:", numpy_array_zeros.shape)
print("Data type:",
numpy_array_zeros.dtype) print("Size:",
numpy_array_zeros.size)
print("Number of dimensions:", numpy_array_zeros.ndim)
print()
print("Array of ones:")
print(numpy_array_ones)
print("Shape:", numpy_array_ones.shape)
print("Data type:",
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
numpy_array_ones.dtype) print("Size:",
numpy_array_ones.size)
print("Number of dimensions:", numpy_array_ones.ndim)
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
Import NumPy: The import numpy as np statement imports the NumPy library and
aliases it as np for convenience.
Create Arrays:
o np.array(python_list) converts a Python list into a NumPy array.
o np.zeros((2, 3)) creates a 2x3 array filled with zeros.
o np.ones((3, 2)) creates a 3x2 array filled with ones.
Display Attributes:
o shape provides the dimensions of the array.
o dtype shows the data type of the elements.
o size gives the total number of elements.
o ndim indicates the number of dimensions.
This program demonstrates how to use NumPy to handle arrays effectively and explore their
attributes.
Conclusion:
In conclusion, writing a program to install NumPy and create arrays using lists and built-in
functions demonstrates the core capabilities of NumPy in handling numerical data
efficiently. By installing NumPy, you gain access to a powerful library for numerical
computations. Creating arrays from lists and using built-in functions allows you to leverage
NumPy’s optimized array operations. Displaying these arrays and their attributes, such as
shape, size, and data type, provides insights into their structure and characteristics. This
exercise is essential for understanding how NumPy simplifies and enhances data
manipulation and mathematical operations in Python.
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 9:
Title/Problem Statement:
Write a program to create a NumPy array and reshape it into different dimensions.
Transpose of the reshaped array and demonstrate swapping axes
Description:
In this task, you will write a program that creates a NumPy array and reshapes it into
different dimensions. After reshaping, you will compute the transpose of the reshaped
array. Additionally, you will demonstrate how to swap axes of the array, showcasing the
flexibility and power of NumPy for array manipulations. This exercise helps in
understanding advanced array operations in NumPy.
Theory:
NumPy is a powerful library in Python used for numerical computations, providing support
for arrays and matrices, along with a variety of mathematical functions to operate on these
data structures. Here, we focus on creating NumPy arrays, reshaping them, and performing
various manipulations such as transposing and swapping axes.
4. Swapping Axes:
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Practical Implementation:
1. Creating a 1D Array:
python
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
4. Swapping Axes:
python
swapped_arr = reshaped_arr.swapaxes(0, 1)
This series of operations demonstrates the flexibility of NumPy arrays in terms of reshaping
and manipulating data structures, which is crucial for various computational tasks in
scientific computing and data analysis.
3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
transposed_array_3x4 =
reshaped_array_3x4.T print("\nTranspose of
3x4 Array:") print(transposed_array_3x4)
Explanation:
1. Creating the Array: The np.arange(12) function creates a 1D array with values from 0
to 11.
2. Reshaping the Array: The reshape() method reshapes the original array into different
dimensions. For example, reshaping into 2x6 or 3x4 arrays.
3. Transposing the Array: The .T attribute is used to transpose the array, which flips its
dimensions. For a 2D array, transposing swaps rows and columns.
4. Swapping Axes: The swapaxes(0, 1) method swaps the axes of the array, changing
the shape accordingly.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Conclusion:
In conclusion, creating and manipulating NumPy arrays is essential for effective numerical
and scientific computing in Python. By writing a program to create a NumPy array and
reshape it into different dimensions, you learn how to structure and reorganize data
efficiently. Transposing the reshaped array illustrates how to switch rows and columns,
providing insights into data transformation. Additionally, demonstrating axis swapping
helps in understanding how to rearrange multidimensional data, which is crucial for various
applications such as data preprocessing, machine learning, and numerical simulations.
These operations showcase the versatility and power of NumPy for handling complex data
structures and performing advanced mathematical operations.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 10:
Title/Problem Statement:
Write a program to create two NumPy arrays and perform element-wise addition,
subtraction, multiplication, and division. Use universal functions to compute square root,
logarithm, and exponential of array elements
Description:
In this task, you will write a program to create two NumPy arrays and perform element-
wise arithmetic operations such as addition, subtraction, multiplication, and division.
Additionally, you will use NumPy's universal functions (ufuncs) to compute the square root,
logarithm, and exponential of the elements in the arrays. This exercise demonstrates the
power and efficiency of NumPy for numerical computations in Python.
Theory:
To work with numerical data efficiently in Python, we often use the NumPy library, which
provides support for large multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays.
In this exercise, you'll start by creating two NumPy arrays, which are essential data
structures in NumPy used for storing and manipulating numerical data. Arrays in NumPy
can be created using the np.array() function, where np is the conventional alias for NumPy.
Once you have created the arrays, you will perform element-wise arithmetic operations
such as addition, subtraction, multiplication, and division. These operations are
straightforward and can be done using the standard arithmetic operators +, -, *, and /,
which NumPy overloads to perform element-wise operations on arrays.
Beyond basic arithmetic, NumPy provides a range of universal functions (ufuncs) that
perform element-wise operations efficiently. You'll use some of these ufuncs to compute
more complex mathematical operations:
Square root: Use np.sqrt(array) to compute the square root of each element in
the array.
Logarithm: Use np.log(array) to compute the natural logarithm of each element
in the array.
Exponential: Use np.exp(array) to compute the exponential (e^x) of each element
in the array.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
# Perform element-wise
operations addition = array1 +
array2 subtraction = array1 -
array2 multiplication = array1 *
array2 division = array1 / array2
# Print results
print("Array 1:", array1)
print("Array 2:", array2)
print("Element-wise Addition:", addition)
print("Element-wise Subtraction:", subtraction)
print("Element-wise Multiplication:", multiplication)
print("Element-wise Division:", division)
print("Square Root of Array 1:", sqrt_array1)
print("Logarithm of Array 1:", log_array1)
print("Exponential of Array 1:", exp_array1)
Explanation:
1. Import NumPy: The program begins by importing the NumPy library, which provides
support for array operations and mathematical functions.
2. Create Arrays: Two NumPy arrays, array1 and array2, are created with example
values.
3. Element-Wise Operations: The program performs element-wise addition,
subtraction, multiplication, and division using standard arithmetic operators. NumPy
handles these operations element-wise by default.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
This program demonstrates how to leverage NumPy for efficient array manipulations and
mathematical computations.
Conclusion:
In conclusion, creating and performing operations on NumPy arrays demonstrates the
power and efficiency of numerical computing in Python. By creating two NumPy arrays and
performing element-wise operations such as addition, subtraction, multiplication, and
division, you can see how NumPy simplifies complex mathematical operations. Utilizing
universal functions (ufuncs) for computing square roots, logarithms, and exponentials
further showcases NumPy’s capability for applying mathematical functions directly to array
elements. These operations are performed efficiently and concisely, making NumPy an
essential tool for data analysis, scientific computing, and numerical tasks.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 11:
Title/Problem Statement:
Write a program to demonstrate various indexing techniques (e.g., accessing specific
elements, rows, columns) and slicing operations to extract subarrays. Include examples of
Boolean and fancy indexing.
Description:
In this program, you will demonstrate various indexing techniques for accessing elements,
rows, and columns in arrays or matrices. You will use slicing to extract subarrays and
showcase Boolean indexing for selecting elements based on conditions. Additionally, you
will illustrate fancy indexing to select specific rows or columns using arrays of indices. This
exercise provides a practical understanding of how to manipulate and access data in arrays
using different indexing methods.
Theory:
In data handling and manipulation, efficient indexing and slicing are crucial for extracting
and modifying data within arrays or data structures like DataFrames. Indexing refers to
accessing specific elements, rows, or columns within a data structure, while slicing allows
for extracting subarrays or subsets of data.
Indexing Techniques
1. Basic Indexing:
o Single Element Access: Access elements using their index positions. For
example, in a list arr, arr[2] retrieves the third element.
o Row/Column Access: In a 2D array or DataFrame, arr[1, 2] or df.iloc[1, 2]
accesses the element in the second row and third column.
2. Boolean Indexing:
o Use Boolean conditions to filter data. For example, arr[arr > 5] returns
elements greater than 5.
o In DataFrames, df[df['column_name'] > 5] filters rows where the specified
column's values are greater than 5.
3. Fancy Indexing:
o Use arrays or lists of indices to access multiple elements simultaneously. For
example, arr[[1, 3, 5]] retrieves the elements at positions 1, 3, and 5.
o In DataFrames, df.iloc[[0, 2, 4], [1, 3]] accesses the specified rows and columns.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Slicing Operations
Basic Slicing:
o Extract subarrays using the : operator. For example, arr[1:5] retrieves elements
from index 1 to 4.
o In 2D arrays or DataFrames, arr[1:4, 2:5] or df.iloc[1:4, 2:5] extracts a subarray
or subset of rows and columns.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation :
This program covers essential indexing techniques and demonstrates how to manipulate
and access data within NumPy arrays effectively.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Conclusion:
In conclusion, demonstrating various indexing techniques and slicing operations in Python
reveals their powerful capabilities for accessing specific elements, rows, and columns, as
well as extracting subarrays. By including examples of Boolean and fancy indexing, you gain
a comprehensive understanding of efficient data manipulation and extraction methods.
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 12:
Title/Problem Statement:
Write a program to create a NumPy array and calculate its mean, median, standard
deviation, and variance. Use advanced statistical methods to compute percentiles and
correlation coefficients.
Description:
In this program, you'll create a NumPy array and compute fundamental statistical metrics
including mean, median, standard deviation, and variance. Additionally, you'll use advanced
statistical methods to calculate percentiles and correlation coefficients. This exercise
demonstrates how to perform comprehensive data analysis using NumPy’s built-in
functions for statistical computations.
Theory:
NumPy is a powerful library in Python for numerical computations, particularly with arrays.
To work with NumPy, you first need to import the library using import numpy as np. You
can create a NumPy array using the np.array() function, passing in a list of numbers. Once
the array is created, NumPy provides various methods to perform statistical operations:
1. Mean: Calculated using np.mean(array), the mean is the average of the array
elements.
2. Median: Found using np.median(array), the median is the middle value when the
array elements are sorted.
3. Standard Deviation: Computed with np.std(array), it measures the amount of
variation or dispersion of the array elements.
4. Variance: Determined using np.var(array), variance is the average of the squared
differences from the mean, indicating how spread out the values are.
Additionally, you can compute percentiles using np.percentile(array, q), where q is the
percentile you want to calculate (e.g., 50 for the median). To measure how much two arrays
vary together, you can use the correlation coefficient, calculated with np.corrcoef(array1,
array2), which returns a matrix of correlation coefficients.
# Calculate mean
mean = np.mean(data)
print(f"Mean: {mean}")
# Calculate median
median = np.median(data)
print(f"Median: {median}")
# Calculate standard
deviation std_dev =
np.std(data)
print(f"Standard Deviation: {std_dev}")
# Calculate variance
variance = np.var(data)
print(f"Variance: {variance}")
# Calculate percentiles
percentiles = np.percentile(data, [25, 50, 75])
print(f"25th Percentile: {percentiles[0]}")
print(f"50th Percentile (Median):
{percentiles[1]}") print(f"75th Percentile:
{percentiles[2]}")
Explanation:
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
3. Median:
o np.median(data) finds the middle value in the sorted array.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
4. Standard Deviation:
o np.std(data) measures the amount of variation or dispersion from the mean.
5. Variance:
o np.var(data) calculates the squared deviation of each element from the mean.
6. Percentiles:
o np.percentile(data, [25, 50, 75]) computes the 25th, 50th (median), and 75th
percentiles.
7. Correlation Coefficient:
o np.corrcoef(data, data2)[0, 1] calculates the Pearson correlation coefficient
between data and data2.
This program provides a comprehensive overview of basic and advanced statistical methods
using NumPy, which is essential for data analysis and scientific computing in Python.
Conclusion:
In conclusion, creating a NumPy array and calculating its mean, median, standard deviation,
variance, percentiles, and correlation coefficients provides a comprehensive understanding
of basic and advanced statistical analysis in Python, leveraging NumPy's powerful
computational capabilities.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 13:
Title/Problem Statement:
Write a program to read data from a CSV file using Pandas. Display the first few rows
(head()), information (info()), and basic statistics (describe()) of the DataFrame. Save the
modified DataFrame to a new CSV file.
Description:
Write a Python program to read data from a CSV file using the Pandas library. First, load the
CSV file into a DataFrame and then display the first few rows with `head()`, the structure
and summary of the DataFrame with `info()`, and basic statistics of the data using
`describe()`. Finally, save the modified DataFrame to a new CSV file to preserve any changes
made during data analysis or manipulation.
Theory:
Pandas is a powerful data manipulation library in Python, widely used for data analysis and
handling structured data. Reading data from a CSV (Comma-Separated Values) file into a
Pandas DataFrame is straightforward using the read_csv() function. This function reads the
CSV file and loads its content into a DataFrame, a tabular data structure with labeled axes
(rows and columns).
To begin, you import the pandas library and use pd.read_csv('filename.csv') to read the CSV
file. The head() method displays the first few rows of the DataFrame, allowing a quick
glance at the data. The info() method provides a concise summary of the DataFrame,
including the number of non-null entries, data types of columns, and memory usage, which
helps in understanding the dataset's structure.
The describe() method generates descriptive statistics of the numerical columns in the
DataFrame, such as mean, standard deviation, minimum, and maximum values, along with
the 25th, 50th (median), and 75th percentiles. This summary gives a quick statistical
overview of the data.
After exploring and possibly modifying the DataFrame (e.g., adding, removing, or
transforming columns), you can save the modified DataFrame back to a CSV file using the
to_csv('new_filename.csv', index=False) method. The index=False argument ensures that
row indices are not written to the new CSV file, maintaining a clean format.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
1. Read Data from CSV: pd.read_csv(file_path) reads the data from the specified CSV
file and creates a DataFrame.
2. Display First Few Rows: df.head() shows the first few rows of the DataFrame,
providing a quick preview of the data.
3. Display Information: df.info() provides a summary of the DataFrame, including data
types, number of non-null values, and memory usage.
4. Display Basic Statistics: df.describe() generates descriptive statistics like mean,
standard deviation, and min/max values for numeric columns.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
5. Modify and Save Data: The DataFrame is optionally modified (e.g., adding a new
column) and then saved to a new CSV file using df.to_csv(output_file_path,
index=False). The index=False argument prevents writing row indices to the CSV file.
Replace file_path and output_file_path with the actual paths to your CSV files and adjust
column names as needed.
Conclusion:
In conclusion, using Pandas to read, explore, and save data from a CSV file streamlines data
analysis by providing easy access to initial data inspection and manipulation, ensuring
efficient handling and storage of modified datasets.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Assignment No 14:
Title/Problem Statement:
Write a program to create a DataFrame from a dictionary of lists. Use methods like head(),
tail(), info(), and describe() to explore and summarize the DataFrame
Description:
In this exercise, you will write a program to create a DataFrame using a dictionary of lists in
Python's pandas library. You will utilize methods such as `head()` to view the first few rows,
`tail()` to see the last few rows, `info()` to get a summary of the DataFrame’s structure and
data types, and `describe()` to generate descriptive statistics. This exercise helps in
understanding DataFrame creation and basic data exploration techniques.
Theory:
Creating a DataFrame from a dictionary of lists is a common task in data analysis using the
pandas library in Python. A DataFrame is a two-dimensional labeled data structure with
columns of potentially different types, similar to a table in a database or an Excel
spreadsheet. Here’s a step-by-step guide to achieve this:
1. Importing pandas: First, you need to import the pandas library, which provides the
DataFrame structure.
import pandas as pd
2. Creating a Dictionary of Lists: Construct a dictionary where the keys are column names
and the values are lists representing the data for each column.
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [70000, 80000, 90000]
}
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
3. Creating the DataFrame: Use the pandas `DataFrame` constructor to create a DataFrame
from the dictionary.
df = pd.DataFrame(data)
4. Exploring the DataFrame: Utilize various methods to explore and summarize the
DataFrame:
- head(): Displays the first few rows of the DataFrame (default is 5).
print(df.head())
- tail(): Displays the last few rows of the DataFrame (default is 5).
print(df.tail())
- info(): Provides a concise summary of the DataFrame, including the index dtype and
column dtypes, non-null values, and memory usage.
print(df.info())
- describe(): Generates descriptive statistics for numeric columns, such as count, mean,
standard deviation, min, and max values.
print(df.describe())
These methods are fundamental for initial data exploration, helping you understand the
structure and basic statistics of the DataFrame. This process is essential in the data analysis
pipeline, providing insights and guiding further data cleaning, processing, and analysis
steps.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
By following these steps, you can efficiently create, explore, and summarize data using
pandas.
print("\n")
print("\n")
print("\n")
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
Explanation:
1. Creating the Dictionary: The data dictionary contains three keys ('Name', 'Age',
'Salary'), each mapped to a list of values.
2. Creating the DataFrame: The pd.DataFrame(data) function converts the dictionary
into a DataFrame.
3. Exploring the DataFrame:
o head(): Shows the first 5 rows of the DataFrame.
o tail(): Shows the last 5 rows of the DataFrame.
o info(): Provides a summary of the DataFrame, including column data types and
non-null counts.
o describe(): Computes and displays descriptive statistics for numeric columns,
such as mean, standard deviation, and range.
This program provides a comprehensive way to initialize a DataFrame and analyze its basic
structure and statistics, making it easier to understand the dataset's characteristics.
Conclusion:
In conclusion, creating a DataFrame from a dictionary of lists and utilizing methods like
`head()`, `tail()`, `info()`, and `describe()` provides a powerful way to manage and analyze
data in Python using the pandas library. By constructing a DataFrame, you can effectively
organize data into a structured format, and these methods offer valuable tools for initial
data exploration. `head()` and `tail()` allow you to quickly view the beginning and end of
your dataset, while `info()` provides a summary of the DataFrame's structure and data
types. The `describe()` method gives a statistical overview of numeric data, helping to
understand data distribution and key metrics. Together, these techniques facilitate a
comprehensive understanding of your data, supporting effective analysis and decision-
making.
5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
6
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-