0% found this document useful (0 votes)
6 views

2 Lab Manual

The document is a lab manual for a Project Based Learning course in Python at Vishwakarma University, Pune, detailing assignments focused on data types, arrays, and file handling. Each assignment includes problem statements, theoretical background, experimental setups, and conclusions to enhance understanding of Python programming concepts. The manual emphasizes practical exercises to develop skills in variable manipulation, data structure performance comparison, and file I/O operations.

Uploaded by

Kedar Ghadge
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

2 Lab Manual

The document is a lab manual for a Project Based Learning course in Python at Vishwakarma University, Pune, detailing assignments focused on data types, arrays, and file handling. Each assignment includes problem statements, theoretical background, experimental setups, and conclusions to enhance understanding of Python programming concepts. The manual emphasizes practical exercises to develop skills in variable manipulation, data structure performance comparison, and file I/O operations.

Uploaded by

Kedar Ghadge
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Vishwakarma University, Pune Project Based Learning-Python Lab

LAB MANUAL

Project Based Learning-Python


(BTECCE23306)

Second Year Engineering

Prof. Mahajan S.V.


PhD (Pursuing) (ME IT)

Assistant Professor

Department of Computer Engineering

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

Experimental Setup / Experimental Outcome:

# Create variables of different data


types integer_var = 10
float_var = 3.14
string_var = "Hello,
World!" boolean_var =
True

# Perform basic operations


int_sum = integer_var + 5
float_product = float_var *
2
string_concat = string_var + " How are you?"
boolean_not = not boolean_var

# Print the results along with their types


print("Integer Variable:", int_sum, "Type:", type(int_sum))
print("Float Variable:", float_product, "Type:", type(float_product))
print("String Variable:", string_concat, "Type:", type(string_concat))
print("Boolean Variable:", boolean_not, "Type:",
type(boolean_not))

Explanation:

1. Variable Creation: Four variables of different types are created:


o integer_var is an integer.
o float_var is a float.
o string_var is a string.
o boolean_var is a Boolean.
2. Basic Operations:
o int_sum: Adds 5 to the integer variable.
o float_product: Multiplies the float variable by 2.
o string_concat: Concatenates the string variable with another string.
o boolean_not: Applies the logical NOT operation on the Boolean variable.

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.

Comparison with Lists:


Performance: Arrays typically provide faster access to elements compared to lists because
they use contiguous memory locations. However, arrays have fixed sizes, which can limit
flexibility.
Lists: In contrast, lists (such as Python's `list`) are dynamic arrays that can grow or shrink in
size. They provide easier insertion and deletion operations but may have overhead due to
their dynamic nature.

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.

Experimental Setup / Experimental Outcome:


import array
import timeit

# Creating an array of integers


arr = array.array('i', [1, 2, 3, 4,
5]) print("Original array:", arr)

# 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()

# Performance comparison with


lists lst = [1, 2, 3, 4, 5]

# Timing array insertion


array_insert_time =
timeit.timeit(
stmt="arr.insert(2, 6)",
setup="from main import arr",
9
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
number=100000

1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

# Timing list insertion


list_insert_time = timeit.timeit(
stmt="lst.insert(2, 6)",
setup="from main import lst",
number=100000
)

# Timing array deletion


array_delete_time =
timeit.timeit(
stmt="arr.remove(4)",
setup="from main import arr",
number=100000
)

# Timing list deletion


list_delete_time =
timeit.timeit(
stmt="lst.remove(4)",
setup="from main import lst",
number=100000
)

# Timing array search


array_search_time =
timeit.timeit(
stmt="arr.index(3)",
setup="from main import arr",
number=100000
)

# Timing list search


list_search_time =
timeit.timeit(
stmt="lst.index(3)",
setup="from main import lst",
number=100000
1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
)

print(f"Array insertion time: {array_insert_time:.6f} seconds")

1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

print(f"List insertion time: {list_insert_time:.6f} seconds")


print(f"Array deletion time: {array_delete_time:.6f} seconds")
print(f"List deletion time: {list_delete_time:.6f} seconds")
print(f"Array search time: {array_search_time:.6f} seconds")
print(f"List search time: {list_search_time:.6f} seconds")

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

Experimental Setup / Experimental Outcome:

def process_file(input_file, output_file):


try:
# Open the input file for reading
with open(input_file, 'r') as infile:
# Initialize
counters
num_lines = 0
num_words = 0
num_characters = 0

# Read the file line by line


for line in infile:
# Update the line count
num_lines += 1

# Update the word count and character count


words = line.split()
num_words += len(words)
num_characters +=
len(line)

# Open the output file for writing


with open(output_file, 'w') as outfile:
# Write the processed data
outfile.write(f"Number of lines: {num_lines}\n")
outfile.write(f"Number of words: {num_words}\n")
outfile.write(f"Number of characters: {num_characters}\n")

print("Data processing complete. Results have been written to", output_file)

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

input_file = 'input.txt' # Replace with your input file name


output_file = 'output.txt' # Replace with your output file name
process_file(input_file, output_file)

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.

Basic Exception Handling:

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.

Custom Exceptions: Define custom exceptions by subclassing Python’s built-in Exception


class. This allows you to create meaningful error messages and handle specific error
conditions in your program.

1
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

Experimental Setup / Experimental Outcome:

# Define custom exceptions


class CustomValueError(Exception):
def init (self, message):
self.message = message
super(). init (self.message)

class CustomTypeError(Exception):
def init (self, message):
self.message = message
super(). init (self.message)

# Function that demonstrates handling various exceptions


def exception_handling_demo(value):
try:
# Example of handling
ValueError if value < 0:
raise ValueError("Value cannot be negative.")

# Example of handling
TypeError if not
isinstance(value, int):
raise TypeError("Value must be an integer.")

# Example of handling FileNotFoundError


try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError as e:
print(f"FileNotFoundError: {e}")

# Example of raising and handling a custom exception


if value == 10:
raise CustomValueError("CustomValueError: Value cannot be 10.")

except ValueError as ve:


print(f"ValueError: {ve}")
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

except TypeError as te:


print(f"TypeError: {te}")
except CustomValueError as cve:
print(f"CustomValueError: {cve}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

# Example usage
print("Testing with a negative
value:") exception_handling_demo(-
5)

print("\nTesting with a non-integer


value:")
exception_handling_demo('string')

print("\nTesting with a valid value that causes FileNotFoundError:")


exception_handling_demo(5)

print("\nTesting with a value that triggers CustomValueError:")


exception_handling_demo(10)

print("\nTesting with a valid value that does not cause any exceptions:")
exception_handling_demo(3)

Explanation:

1. Custom Exceptions: The CustomValueError and CustomTypeError classes are custom


exceptions derived from the base Exception class. They are used to handle specific
error conditions.
2. Function exception_handling_demo(value):
o ValueError Handling: Raises a ValueError if the input value is negative.
o TypeError Handling: Raises a TypeError if the input value is not an integer.
o FileNotFoundError Handling: Attempts to open a file that does not exist,
catching the FileNotFoundError and printing an error message.
o Custom Exception Handling: Raises a CustomValueError if the input value is
10, demonstrating how to handle custom exceptions.
o General Exception Handling: Catches any other unexpected exceptions.
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab
3. Example Usage:

2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

o Negative Value: Tests how the program handles a ValueError.


o Non-integer Value: Tests how the program handles a TypeError.
o File Not Found: Tests the handling of a FileNotFoundError.
o Custom Exception: Tests the custom exception handling.
o Valid Value: Tests the scenario where no exceptions are raised.

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:

In Python, a constructor is a special method used to initialize a newly created object of


a class. It is defined using the init () method within a class. When a new object is
instantiated, Python automatically calls this constructor to set up the initial state of the
object.

Here’s how a constructor works:

1. Define a Class: Create a class using the class keyword.


2. Implement the Constructor: Inside the class, define the init () method. This
method can take parameters that are used to initialize the object's attributes.
3. Create an Object: When you create an instance of the class, you pass arguments
to the class name. Python calls the init () method with these arguments to set up
the object.

Experimental Setup / Experimental Outcome:


class Person:
def init (self, name, age):
# Constructor method to initialize
attributes self.name = name
self.age = age

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}")

# Creating an instance of the Person


class person1 = Person("Alice", 30)

# Calling the display_info method to show the initialized attributes


person1.display_info()

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.

Here's a simplified explanation and example:

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.

Experimental Setup / Experimental Outcome:


from abc import ABC, abstractmethod

# Define an interface using an abstract base class


class Shape(ABC):

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

# Implement the interface in a concrete class


class Rectangle(Shape):
def init (self, width,
height): self.width = width
self.height = height

def area(self):
return self.width * self.height

def perimeter(self):
return 2 * (self.width + self.height)

# Implement the interface in another concrete class


class Circle(Shape):
def init (self,
radius): self.radius =
radius

def area(self):
import math
return math.pi * self.radius ** 2

def perimeter(self):
import math
return 2 * math.pi * self.radius

# Instantiate objects of the concrete classes


rectangle = Rectangle(5, 3)
circle = Circle(4)
2
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

# Demonstrate the use of the


interface def print_shape_info(shape):
print(f"Area: {shape.area()}")
print(f"Perimeter: {shape.perimeter()}")

print("Rectangle Information:")
print_shape_info(rectangle)

print("\nCircle Information:")
print_shape_info(circle)

Explanation:

1. Abstract Base Class (Interface):


o Shape is an abstract base class that serves as an interface with two abstract
methods: area() and perimeter(). These methods are defined but not
implemented, which means any class inheriting from Shape must provide
concrete implementations for these methods.
2. Concrete Implementations:
o Rectangle and Circle are concrete classes that inherit from Shape. They provide
specific implementations for the area() and perimeter() methods.
3. Instantiation and Usage:
o Objects of Rectangle and Circle are created with specific dimensions. The
print_shape_info function demonstrates how to use these objects and their
methods, relying on the interface provided by Shape.

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:

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a


class to inherit attributes and methods from another class. This helps in code reusability
and organization. In Python, you can demonstrate inheritance by creating a base class (also
known as a parent or superclass) and one or more derived classes (also known as child or
subclasses) that inherit from the base class.

Here’s a simple example to illustrate inheritance:

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.

Experimental Setup / Experimental Outcome:


# Base class
class Animal:
def init (self, name):
self.name = name

def speak(self):

3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

return "Some generic sound"

def str (self):


return f"Animal: {self.name}"

# 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 str (self):


return f"Dog: {self.name}, Breed: {self.breed}"

# Another derived class


class Cat(Animal):
def init (self, name, color):
super(). init (name) # Call the constructor of the base class
self.color = color

def speak(self):
return "Meow!"

def str (self):


return f"Cat: {self.name}, Color: {self.color}"

# Demonstration
def main():
# Create instances of Dog and Cat
dog = Dog(name="Buddy", breed="Golden Retriever")
cat = Cat(name="Whiskers", color="Black")

# Use methods from base and derived classes


print(dog) # Output: Dog: Buddy, Breed: Golden
Retriever print(dog.speak()) # Output: Woof!

3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

print(cat) # Output: Cat: Whiskers, Color:


Black print(cat.speak()) # Output: Meow!

if name == " main ":


main()

Explanation:

1. Base Class (Animal):


o init method initializes the name attribute.
o speak method provides a generic sound.
o str method returns a string representation of the animal.
2. Derived Class (Dog):
o Inherits from Animal.
o Adds an additional attribute breed.
o Overrides the speak method to return "Woof!".
o Overrides the str method to include breed information.
3. Another Derived Class (Cat):
o Inherits from Animal.
o Adds an additional attribute color.
o Overrides the speak method to return "Meow!".
o Overrides the str method to include color information.
4. Demonstration:
o Instances of Dog and Cat are created.
o Methods from both the base class and derived classes are used to show how
inheritance allows extending and modifying behavior.

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

Experimental Setup / Experimental Outcome:

pip install numpy


# Import the NumPy library
import numpy as np

# Create a NumPy array from a Python list


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

# Create a NumPy array using a built-in function (e.g., zeros,


ones) numpy_array_zeros = np.zeros((2, 3)) # 2x3 array of zeros
numpy_array_ones = np.ones((3, 2)) # 3x2 array of ones

# Display the created arrays


print("Array created from a Python
list:") print(numpy_array_from_list)
print("Shape:", numpy_array_from_list.shape)
print("Data type:",
numpy_array_from_list.dtype) print("Size:",
numpy_array_from_list.size)
print("Number of dimensions:", numpy_array_from_list.ndim)
print()

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.

1. Creating a NumPy Array:


- You can create a NumPy array using the `numpy.array()` function, which takes a list (or
nested lists for multi-dimensional arrays) as input.
- Example: `arr = np.array([1, 2, 3, 4, 5, 6])`

2. Reshaping the Array:


- Reshaping means changing the shape of the array without altering its data.
- This can be done using the `reshape()` method, specifying the new dimensions.
- Example: `reshaped_arr = arr.reshape(2, 3)` converts a 1D array of 6 elements into a 2D
array with 2 rows and 3 columns.

3. Transposing the Array:


- Transposing flips the dimensions of the array, converting rows to columns and vice versa.
- This is achieved using the `transpose()` method.
- Example: `transposed_arr = reshaped_arr.transpose()` switches the rows and columns of
the 2D array.

4. Swapping Axes:

3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

- Swapping axes means interchanging two specified axes of the array.


- The `swapaxes()` method is used for this, which takes two axis indices as arguments.
- Example: `swapped_arr = reshaped_arr.swapaxes(0, 1)` swaps the first and second axes
of the 2D array.

Practical Implementation:
1. Creating a 1D Array:
python
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])

2. Reshaping the Array:


python
reshaped_arr = arr.reshape(2, 3)

3. Transposing the Array:


python
transposed_arr = reshaped_arr.transpose()

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.

Experimental Setup / Experimental Outcome:


import numpy as np

# Step 1: Create a NumPy array


array = np.arange(12) # Creates a 1D array with values from 0 to 11
print("Original Array:")
print(array)

3
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

# Step 2: Reshape the array into different dimensions


reshaped_array_2x6 = array.reshape(2, 6) # Reshape into a 2x6 array
print("\nReshaped Array (2x6):")
print(reshaped_array_2x6)

reshaped_array_3x4 = array.reshape(3, 4) # Reshape into a 3x4 array


print("\nReshaped Array (3x4):")
print(reshaped_array_3x4)

# Step 3: Transpose of the reshaped array


transposed_array_2x6 =
reshaped_array_2x6.T print("\nTranspose of
2x6 Array:") print(transposed_array_2x6)

transposed_array_3x4 =
reshaped_array_3x4.T print("\nTranspose of
3x4 Array:") print(transposed_array_3x4)

# Step 4: Demonstrate swapping axes


swapped_axes_array = reshaped_array_3x4.swapaxes(0, 1) # Swap axes of the 3x4 array
print("\nArray with Swapped Axes (3x4 to 4x3):")
print(swapped_axes_array)

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.

This program demonstrates how to manipulate NumPy arrays effectively, showcasing


reshaping, transposing, and axis swapping operations.

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

Experimental Setup / Experimental Outcome:


import numpy as np

# Create two NumPy arrays


array1 = np.array([10, 20, 30, 40, 50])
array2 = np.array([1, 2, 3, 4, 5])

# Perform element-wise
operations addition = array1 +
array2 subtraction = array1 -
array2 multiplication = array1 *
array2 division = array1 / array2

# Use universal functions


sqrt_array1 = np.sqrt(array1)
log_array1 = np.log(array1)
exp_array1 = np.exp(array1)

# 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

4. Universal Functions: The program uses NumPy's universal functions (np.sqrt(),


np.log(), and np.exp()) to compute the square root, natural logarithm, and
exponential of the elements in array1.
5. Print Results: Finally, the program prints the original arrays and the results of the
various operations.

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.

Experimental Setup / Experimental Outcome:


import numpy as np

# Create a 2D NumPy array


(matrix) array = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])

# Display the original


array print("Original
Array:") print(array)

# Accessing specific elements print("\


nAccessing Specific Elements:")
print("Element at (1, 2):", array[1, 2]) # Output: 7

# Accessing specific rows and columns print("\


nAccessing Specific Rows and Columns:")
print("Row 1:", array[1]) # Output: [5, 6, 7, 8]
print("Column 2:", array[:, 2]) # Output: [3, 7, 11]

# Slicing operations print("\


nSlicing Operations:")
print("First two rows and columns (2x2 subarray):")
print(array[:2, :2]) # Output: [[1, 2], [5, 6]]

print("All rows and last two columns:")

4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

print(array[:, -2:]) # Output: [[ 3, 4], [ 7, 8], [11, 12]]

# Boolean indexing print("\


nBoolean Indexing:") mask =
array > 5
print("Array with elements greater than 5:")
print(array[mask]) # Output: [ 6, 7, 8, 9, 10, 11, 12]

# Fancy indexing print("\


nFancy Indexing:") rows =
[0, 2]
cols = [1, 3]
print("Elements from specified rows and columns:")
print(array[rows, cols]) # Output: [ 2, 12]

Explanation :

1. Creating the Array:


o A 2D NumPy array array is created with predefined values.
2. Accessing Specific Elements:
o Access elements using row and column indices. For example, array[1, 2]
retrieves the element in the second row and third column.
3. Accessing Specific Rows and Columns:
o Retrieve an entire row with array[1] and an entire column with array[:, 2].
4. Slicing Operations:
o Extract subarrays using slicing. For example, array[:2, :2] gets the top-left 2x2
subarray, and array[:, -2:] gets the last two columns of all rows.
5. Boolean Indexing:
o Use a Boolean mask to filter elements. For example, array > 5 creates a
Boolean mask to select elements greater than 5.
6. Fancy Indexing:
o Use lists of indices to select specific elements from the array. For example,
array[rows, cols] selects elements from specified rows and columns.

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.

Experimental Setup / Experimental Outcome:


import numpy as np

# Create a NumPy array


data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
4
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

# 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]}")

# Create another NumPy array for correlation example


data2 = np.array([15, 25, 35, 45, 55, 65, 75, 85, 95, 105])

# Calculate correlation coefficient between two


arrays correlation = np.corrcoef(data, data2)[0, 1]
print(f"Correlation Coefficient: {correlation}")

Explanation:

1. Creating the Array:


o data = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) initializes a NumPy
array with 10 integers.
2. Mean:
o np.mean(data) computes the average of the array elements.

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

Experimental Setup / Experimental Outcome:


import pandas as pd

# Step 1: Read data from a CSV file


file_path = 'data.csv' # Replace with the path to your CSV file
df = pd.read_csv(file_path)

# Step 2: Display the first few rows of the DataFrame


print("First few rows of the DataFrame:")
print(df.head())

# Step 3: Display information about the DataFrame


print("\nInformation about the DataFrame:")
print(df.info())

# Step 4: Display basic statistics of the DataFrame


print("\nBasic statistics of the DataFrame:")
print(df.describe())

# Optional: Modify the DataFrame (example: adding a new column)


df['NewColumn'] = df['ExistingColumn'] * 2 # Replace 'ExistingColumn' with an actual
column name

# Step 5: Save the modified DataFrame to a new CSV file


output_file_path = 'modified_data.csv' # Path for the new CSV file
df.to_csv(output_file_path, index=False)

print(f"\nModified DataFrame saved to {output_file_path}")

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.

Experimental Setup / Experimental Outcome:


import pandas as pd

# Step 1: Create a dictionary of


lists data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [25, 30, 35, 40, 45],
'Salary': [70000, 80000, 90000, 100000, 110000]
}

# Step 2: Create a DataFrame from the dictionary


df = pd.DataFrame(data)

# Step 3: Explore the DataFrame using various methods

# Display the first few rows of the DataFrame


print("First few rows of the DataFrame:")
print(df.head())

print("\n")

# Display the last few rows of the DataFrame


print("Last few rows of the DataFrame:")
print(df.tail())

print("\n")

# Display a concise summary of the DataFrame


print("Summary of the DataFrame:")
print(df.info())

print("\n")

# Display descriptive statistics of the DataFrame

5
- Faculty: Prof. Sagar V. Mahajan (Whatsapp-
Vishwakarma University, Pune Project Based Learning-Python Lab

print("Descriptive statistics of the


DataFrame:") print(df.describe())

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-

You might also like