0% found this document useful (0 votes)
5 views41 pages

data science

The document outlines a practical course in Data Science using Python at Dhanalakshmi Srinivasan Arts and Science College. It includes various experiments focusing on flow control, functions, and string manipulations, detailing objectives, algorithms, and example programs for each topic. The document serves as a certification of work done by students in the third semester during the academic year 2024-2025.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views41 pages

data science

The document outlines a practical course in Data Science using Python at Dhanalakshmi Srinivasan Arts and Science College. It includes various experiments focusing on flow control, functions, and string manipulations, detailing objectives, algorithms, and example programs for each topic. The document serves as a certification of work done by students in the third semester during the academic year 2024-2025.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

DHANALAKSHMI SRINIVASAN ARTS AND SCIENCE (CO-EDUCATION) COLLEGE

(Affiliated to the University of Madras)


ECR, MAMALLAPURAM, Chennai - 603 104

DEPARTMENT OF COMPUTER SCIENCE WITH DATA SCIENCE

DATA SCIENCE USING PYTHON PRACTICAL

STUDENT NAME :

CLASS :

REGISTER NUMBER :
SEMESTER :
DHANALAKSHMI SRINIVASAN ARTS AND SCIENCE (Co-Education) COLLEGE
(Affiliated to University of Madras)

ECR, MAMALLAPURAM, CHENNAI -603 104

REGISTER NUMBER :

DEPARTMENT : COMPUTER SCIENCE WITH DATA SCIENCE

SUBJECT : DATA SCIENCE USING PYTHON PRACTICAL

SUBJECT CODE :

This is to certify that this is a bonafide record of work done by


of THIRD semester in the
DATA SCIENCE USING PYTHON PRACTICAL during the Academic year 2024-2025.

Signature of Staff in-Charge Signature of the HOD

Submitted for the Practical Examination held on

Internal Examiner External Examiner


CONTENTS

S.NO DATE NAME OF THE EXPERIMENT PAGE STAFF SIGN


NO
1 Editing and executing Programs involving Flow
Controls.
2 Editing and executing Programs involving Functions

3 Program in String Manipulations

4 Creating and manipulating a Tuple

5 Creating and manipulating a List

6 Creating and manipulating a Dictionary

7 Object Creation and Usage


8 Program involving Inheritance

9 Program involving Overloading

10 Reading and Writing with Text Files and Binary Files

11 Combining and Merging Data Sets

12 Program involving Regular Expressions

13 Data Aggregation and Group Wise Operations


Ex no: 01 Editing and executing Programs involving Flow Controls.

Date:

Aim:
To develop, edit, and execute programs that utilize flow control structures (such as conditional
statements and loops) to manage the execution flow based on conditions and iterations.

Algorithm:

1. Start
2. Define the problem statement and identify the required flow control structures (e.g., if-
else, for loop, while loop).
3. Write the program using a suitable programming language.
4. Implement flow control structures such as:
Conditional Statements: if, if-else, nested if
Loops: for, while, do-while
5. Edit and refine the program to ensure correctness and efficiency.
6. Execute the program and check for errors or logical mistakes.
7. Test the program with various inputs to validate its correctness.
8. Debug and optimize the program if necessary.
9. Document the program with comments for better understanding.
10. Step 10: End

PROGRAM:

# A simple program to demonstrate flow control structures


def flow_control_program():
print("Welcome to the Flow Control Program!")
print("You can choose different flow control options to execute the program.")

while True:
print("\nSelect an option to execute:")
print("1. If-Else Condition")
print("2. For Loop")
4
print("3. While Loop")
print("4. Nested Loops")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '1':
# If-Else Condition Example
print("\nYou selected If-Else Condition.")
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is positive.")
elif number < 0:
print(f"{number} is negative.")
else:
print(f"{number} is zero.")

elif choice == '2':


# For Loop Example
print("\nYou selected For Loop.")
n = int(input("Enter a number for the range: "))
print(f"Looping from 1 to {n}:")
for i in range(1, n + 1):
print(f"Iteration {i}")

elif choice == '3':


# While Loop Example
print("\nYou selected While Loop.")
count = 0
n = int(input("Enter the number of iterations: "))
print(f"Counting from 1 to {n}:")
while count < n:
count += 1
print(f"Iteration {count}")

elif choice == '4':


# Nested Loops Example
print("\nYou selected Nested Loops.")
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
print("Printing a grid of numbers:")
for i in range(rows):
for j in range(columns):
print(f"({i+1}, {j+1})", end=" ")
print()

elif choice == '5':


print("Exiting the program. Goodbye!")
break # Break out of the loop to exit the program
5
else:
print("Invalid choice. Please enter a number between 1 and 5.")

if __name__ == "__main__":
flow_control_program()

OUTPUT:
Welcome to the Flow Control Program!
You can choose different flow control options to execute the program.

Select an option to execute:


1. If-Else Condition
2. For Loop
3. While Loop
4. Nested Loops
5. Exit
Enter your choice (1-5): 1

You selected If-Else Condition.


Enter a number: 5
5 is positive.

Select an option to execute:


1. If-Else Condition
2. For Loop
3. While Loop
4. Nested Loops
5. Exit
Enter your choice (1-5): 2

You selected For Loop.


Enter a number for the range: 8
Looping from 1 to 8:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8

Select an option to execute:


1. If-Else Condition
2. For Loop
3. While Loop
4. Nested Loops
6
5. Exit
Enter your choice (1-5): 3

You selected While Loop.


Enter the number of iterations: 7
Counting from 1 to 7:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7

Select an option to execute:


1. If-Else Condition
2. For Loop
3. While Loop
4. Nested Loops
5. Exit
Enter your choice (1-5): 4

You selected Nested Loops.


Enter the number of rows: 5
Enter the number of columns: 5
Printing a grid of numbers:
(1, 1) (1, 2) (1, 3) (1, 4) (1, 5)
(2, 1) (2, 2) (2, 3) (2, 4) (2, 5)
(3, 1) (3, 2) (3, 3) (3, 4) (3, 5)
(4, 1) (4, 2) (4, 3) (4, 4) (4, 5)
(5, 1) (5, 2) (5, 3) (5, 4) (5, 5)

Select an option to execute:


1. If-Else Condition
2. For Loop
3. While Loop
4. Nested Loops
5. Exit
Enter your choice (1-5): 5
Exiting the program. Goodbye!

Result:

7
Ex no:02 Editing and executing Programs involving Functions
Date:

Aim:

To develop, edit, and execute Python programs that utilize functions to modularize code, improve
readability, and enhance reusability.

Algorithm:

1. Start

2. Define the problem statement and identify the need for functions.

3. Write function definitions including:

Functions with parameters

Functions returning values

Functions with default arguments (if needed)

4. Implement function calls within the program.

5. Edit and refine the program to improve efficiency and clarity.

6. Execute the program and verify the correctness of function outputs.

7. Test the program with various inputs and edge cases.

8. Debug and optimize the code if necessary.

9. Document the program with appropriate comments for better understanding.

10. End

PROGRAM:

# Function definitions to demonstrate various concepts

def add(a, b):


"""Function to add two numbers."""
return a + b

8
def subtract(a, b):
"""Function to subtract b from a."""
return a - b

def multiply(a, b):


"""Function to multiply two numbers."""
return a * b

def divide(a, b):


"""Function to divide a by b (with error handling for division by zero)."""
if b == 0:
return "Error! Division by zero."
return a / b

def power(a, b):


"""Function to calculate a raised to the power of b."""
return a ** b

def factorial(n):
"""Function to calculate factorial of a number."""
if n < 0:
return "Error! Factorial of a negative number doesn't exist."
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

def main_program():
print("Welcome to the Function Execution Program!")
print("You can choose from several mathematical functions to execute.")

while True:
print("\nSelect a function to execute:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Power (Exponentiation)")
print("6. Factorial")
print("7. Exit")

choice = input("Enter your choice (1-7): ")

if choice == '1': 9
print("\nYou selected Addition.")
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
print(f"The result of {a} + {b} is: {add(a, b)}")

elif choice == '2':


print("\nYou selected Subtraction.")
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
print(f"The result of {a} - {b} is: {subtract(a, b)}")

elif choice == '3':


print("\nYou selected Multiplication.")
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
print(f"The result of {a} * {b} is: {multiply(a, b)}")

elif choice == '4':


print("\nYou selected Division.")
a = float(input("Enter the numerator: "))
b = float(input("Enter the denominator: "))
print(f"The result of {a} / {b} is: {divide(a, b)}")

elif choice == '5':


print("\nYou selected Power (Exponentiation).")
a = float(input("Enter the base number: "))
b = float(input("Enter the exponent: "))
print(f"The result of {a} raised to the power of {b} is: {power(a, b)}")

elif choice == '6':


print("\nYou selected Factorial.")
n = int(input("Enter a number to calculate its factorial: "))
print(f"The factorial of {n} is: {factorial(n)}")

elif choice == '7':


print("Exiting the program. Goodbye!")
break # Exit the loop and the program

else:
print("Invalid choice. Please enter a number between 1 and 7.")

if __name__ == "__main__":
main_program()

OUTPUT:
Welcome to the Function Execution Program!
You can choose from several mathematical functions to execute.

Select a function to execute:


1. Add 10
2. Subtract
3. Multiply
4. Divide
5. Power (Exponentiation)
6. Factorial
7. Exit
Enter your choice (1-7): 1

You selected Addition.


Enter the first number: 10
Enter the second number: 20
The result of 10.0 + 20.0 is: 30.0

Result:

11
Ex no:03 Program in String Manipulations
Date:

Aim:

To develop a Python program for reading and writing operations on both text files and binary files,
ensuring efficient file handling.

Algorithm:

For Text Files:

1. Start

2. Open a text file in the required mode (read, write, append, etc.).

3. Perform operations:

Read data from the file

Write data to the file

Append data if needed


4. Close the file to free system resources.

5. Reopen and verify the file content (if required).

6. End

For Binary Files:

1. Start

2. Open a binary file in the required mode (rb for reading, wb for writing, ab for appending).

3. Perform operations:

4. Read binary data from the file

5. Write binary data (e.g., images, audio, serialized objects)

6. Close the file to ensure data integrity.

7. Reopen and verify the file content (if required).

8. End
12
Program:

def string_manipulation():
# Sample string for manipulation
original_string = "Hello, Python Programming!"

# 1. String Length

print(f"Length of string: {len(original_string)}")

# 2. String to Uppercase
print(f"Uppercase: {original_string.upper()}")

# 3. String to Lowercase
print(f"Lowercase: {original_string.lower()}")

# 4. Check if string starts with a particular substring


print(f"Starts with 'Hello': {original_string.startswith('Hello')}")

# 5. Check if string ends with a particular substring


print(f"Ends with 'Programming!': {original_string.endswith('Programming!')}")

# 6. Replace part of the string


replaced_string = original_string.replace("Python", "Java")
print(f"Replaced string: {replaced_string}")

# 7. Split string by a delimiter (e.g., space)


split_string = original_string.split(" ")
print(f"Split string: {split_string}")

# 8. Find the index of a substring


index_of_python = original_string.find("Python")
print(f"Index of 'Python': {index_of_python}")

# 9. Remove leading/trailing spaces


string_with_spaces = " Hello, World! "
print(f"String after stripping spaces: '{string_with_spaces.strip()}'")

# 10. Check if a substring is present in the string


is_substring = "Python" in original_string
print(f"Is 'Python' in the string: {is_substring}")

# 11. Concatenate strings


string2 = " Let's Learn!"
concatenated_string = original_string + string2
print(f"Concatenated string: {concatenated_string}")

# 12. Count occurrences of a substring


13
count_python = original_string.count("Python")
print(f"Count of 'Python': {count_python}")

# 13. Capitalize the first letter of the string


print(f"Capitalized: {original_string.capitalize()}")

# 14. Convert string into a list of characters


char_list = list(original_string)
print(f"String as a list of characters: {char_list}")

# Run the function


string_manipulation()

Output:

Length of string: 24
Uppercase: HELLO, PYTHON PROGRAMMING!
Lowercase: hello, python programming!
Starts with 'Hello': True
Ends with 'Programming!': True
Replaced string: Hello, Java Programming!
Split string: ['Hello,', 'Python', 'Programming!']
Index of 'Python': 7
String after stripping spaces: 'Hello, World!'
Is 'Python' in the string: True
Concatenated string: Hello, Python Programming! Let's Learn!
Count of 'Python': 1
Capitalized: Hello, python programming!
String as a list of characters: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'P', 'r', 'o', 'g', 'r ', 'a', 'm', 'm','i', 'n', 'g',
'!']

Result:

14
Ex no:04 Creating and manipulating a Tuple
Date:

AIM:

To develop a Python program for creating and manipulating tuples, including operations such as accessing
elements, slicing, updating, concatenation, repetition, deletion, and built-in tuple functions.

ALGORITHM:
Step 1: Start the program.
Step 2: Create a tuple with multiple elements.
Step 3: Access elements using indexing and slicing.
Step 4: Perform tuple operations such as:
Concatenation (+)
Repetition (*)
Membership checking (in, not in)
Step 5: Demonstrate built-in tuple functions like len(), max(), min(), count(), and index().
Step 6: Show that tuples are immutable by attempting to modify an element (which results in an error).
Step 7: Delete a tuple using del.
Step 8: Display the results.
Step 9: End the program.

Porgram:

def tuple_manipulation():
# 1. Creating a tuple
my_tuple = (1, 2, 3, "Python", 5.5)
print(f"Original Tuple: {my_tuple}")

# 2. Accessing tuple elements


print(f"Element at index 3: {my_tuple[3]}") # Accessing element by index

# 3. Tuple slicing
sliced_tuple = my_tuple[1:4] # Slicing from index 1 to 3
print(f"Sliced Tuple (index 1 to 3): {sliced_tuple}")

# 4. Concatenating tuples
another_tuple = ("Java", "C++")
concatenated_tuple = my_tuple + another_tuple
15
print(f"Concatenated Tuple: {concatenated_tuple}")

# 5. Repeating tuples
repeated_tuple = my_tuple * 2
print(f"Repeated Tuple (2 times): {repeated_tuple}")

# 6. Finding the length of a tuple


print(f"Length of the tuple: {len(my_tuple)}")

# 7. Checking if an element exists in the tuple


print(f"Is 'Python' in the tuple? {'Python' in my_tuple}")

# 8. Tuple indexing (negative indexing)


print(f"Element at last index: {my_tuple[-1]}") # Negative indexing to access the last element

# 9. Iterating over a tuple


print("Iterating over the tuple:")
for item in my_tuple:
print(item)

# 10. Counting occurrences of an element


count = my_tuple.count(2)
print(f"Count of element '2': {count}")

# 11. Finding the index of an element


index_of_python = my_tuple.index("Python")
print(f"Index of 'Python': {index_of_python}")

# Run the function


tuple_manipulation()

Output:

Original Tuple: (1, 2, 3, 'Python', 5.5)


Element at index 3: Python
Sliced Tuple (index 1 to 3): (2, 3, 'Python')
Concatenated Tuple: (1, 2, 3, 'Python', 5.5, 'Java', 'C++')
Repeated Tuple (2 times): (1, 2, 3, 'Python', 5.5, 1, 2, 3, 'Python', 5.5)
Length of the tuple: 5
Is 'Python' in the tuple? True
Element at last index: 5.5
Iterating over the tuple:
1
2
3
Python
5.5
Count of element '2': 1
Index of 'Python': 3
16
RESULT:

17
Ex no: Creating and manipulating a List
Date:

AIM:
To understand and implement the creation and manipulation of a list in a programming language.

ALGORITHM:

1. Start

2. Declare and Initialize a List

3. Define a list with elements or an empty list.

4. Add Elements to the List

5. Use appropriate methods (e.g., append(), add(), etc.) to insert elements.

6. Access Elements from the List

7. Retrieve elements using indexing or iteration.

8. Modify Elements in the List

9. Update elements using index-based assignment.

10. Remove Elements from the List

11. Use methods like remove(), pop(), or slicing to delete elements.

12. Perform Other List Operations

13. Sorting, reversing, searching, slicing, etc.

14. Display the List

15. Print or return the list after modifications.

16. Terminate the Program

17. End

Program:

18
def list_manipulation():
# 1. Creating a list
my_list = [1, 2, 3, "Python", 5.5, True]
print(f"Original List: {my_list}")

# 2. Accessing list elements


print(f"Element at index 3: {my_list[3]}") # Accessing element by index

# 3. List slicing
sliced_list = my_list[1:4] # Slicing from index 1 to 3
print(f"Sliced List (index 1 to 3): {sliced_list}")

# 4. Appending an element
my_list.append("New Element")
print(f"List after appending an element: {my_list}")

# 5. Inserting an element at a specific index


my_list.insert(2, "Inserted Element")
print(f"List after inserting an element at index 2: {my_list}")

# 6. Removing an element
my_list.remove("Python")
print(f"List after removing 'Python': {my_list}")

# 7. Popping an element by index (returns the removed element)


popped_element = my_list.pop(1)
print(f"List after popping element at index 1: {my_list}")
print(f"Popped Element: {popped_element}")

# 8. Counting occurrences of an element


count_of_2 = my_list.count(2)
print(f"Count of element '2': {count_of_2}")

# 9. Finding the index of an element


index_of_5_5 = my_list.index(5.5)
print(f"Index of '5.5': {index_of_5_5}")

# 10. Sorting the list (for elements that are comparable)


number_list = [3, 1, 5, 2, 4]
number_list.sort() # Sorts the list in ascending order
print(f"Sorted List: {number_list}")

# 11. Reversing the list


number_list.reverse() # Reverses the list
print(f"Reversed List: {number_list}")

# 12. Extending the list with another list


another_list = ["Java", "C++"]
my_list.extend(another_list)
print(f"List after extending with another list: {my_list}")19
# 13. Iterating over a list
print("Iterating over the list:")
for item in my_list:
print(item)

# 14. Checking if an element exists in the list


is_python_present = "Python" in my_list
print(f"Is 'Python' in the list? {is_python_present}")

# 15. Getting the length of the list


print(f"Length of the list: {len(my_list)}")

# Run the function


list_manipulation()

Output:

Original List: [1, 2, 3, 'Python', 5.5, True]


Element at index 3: Python
Sliced List (index 1 to 3): [2, 3, 'Python']
List after appending an element: [1, 2, 3, 'Python', 5.5, True, 'New Element']
List after inserting an element at index 2: [1, 2, 'Inserted Element', 3, 'Python', 5.5, True, 'New
Element']
List after removing 'Python': [1, 2, 'Inserted Element', 3, 5.5, True, 'New Element']
List after popping element at index 1: [1, 'Inserted Element', 3, 5.5, True, 'New Element']
Popped Element: 2
Count of element '2': 0
Index of '5.5': 3
Sorted List: [1, 2, 3, 4, 5]
Reversed List: [5, 4, 3, 2, 1]
List after extending with another list: [1, 'Inserted Element', 3, 5.5, True, 'New Element', 'Java', 'C++']
Iterating over the list:
1
Inserted Element
3
5.5
True
New Element
Java
C++
Is 'Python' in the list? False
Length of the list: 8

RESULT:
20
Ex no:06 Creating and manipulating a Dictionary
Date:

AIM:

To understand and implement the creation and manipulation of a dictionary in a programming


language.

ALGORITHM:

1. Start

2. Create a Dictionary

3. Define an empty dictionary or initialize it with key-value pairs.

4. Add Elements to the Dictionary

5. Insert new key-value pairs using the appropriate syntax or method.

6. Access Elements from the Dictionary

7. Retrieve values using their corresponding keys.

8. Modify Elements in the Dictionary

9. Update values associated with specific keys.

10. Remove Elements from the Dictionary

11. Use methods like del, pop(), or popitem() to remove items.

12. Perform Other Dictionary Operations

13. Get all keys, values, or items, check for the existence of a key, iterate through the dictionary,
etc.

14. Display the Dictionary

15. Print or return the dictionary after modifications.

16. Terminate the Program

17. End

21
Program:

def dictionary_manipulation():
# 1. Creating a dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York",
"is_student": False
}
print(f"Original Dictionary: {my_dict}")

# 2. Accessing dictionary elements


print(f"Value of 'name': {my_dict['name']}") # Accessing by key

# 3. Adding or updating an element


my_dict["age"] = 31 # Update existing key
my_dict["country"] = "USA" # Add a new key-value pair
print(f"Dictionary after adding/updating: {my_dict}")

# 4. Removing an element by key


del my_dict["is_student"] # Removes the key-value pair
print(f"Dictionary after removing 'is_student': {my_dict}")

# 5. Using the pop method to remove an element and get its value
removed_value = my_dict.pop("city")
print(f"Dictionary after popping 'city': {my_dict}")
print(f"Removed 'city' value: {removed_value}")

# 6. Getting the keys, values, and items of a dictionary


print(f"Keys of the dictionary: {my_dict.keys()}")
print(f"Values of the dictionary: {my_dict.values()}")
print(f"Items (key-value pairs) of the dictionary: {my_dict.items()}")

# 7. Checking if a key exists in the dictionary


is_name_present = "name" in my_dict
print(f"Is 'name' a key in the dictionary? {is_name_present}")

# 8. Iterating through the dictionary


print("Iterating through the dictionary:")
for key, value in my_dict.items():
print(f"{key}: {value}")

# 9. Merging two dictionaries


another_dict = {"gender": "Male", "occupation": "Engineer"}
my_dict.update(another_dict) # Merges another dictionary into the original one
print(f"Dictionary after merging with another dictionary: {my_dict}")

# 10. Copying a dictionary


copied_dict = my_dict.copy() # Creates a shallow copy 22
print(f"Copied Dictionary: {copied_dict}")

# 11. Clearing all elements from the dictionary


my_dict.clear() # Removes all key-value pairs
print(f"Dictionary after clearing all elements: {my_dict}")

# Run the function


dictionary_manipulation()

Output:

Original Dictionary: {'name': 'John', 'age': 30, 'city': 'New York', 'is_student': False}
Dictionary after adding/updating: {'name': 'John', 'age': 31, 'city': 'New York', 'is_student': False, 'country':
'USA'}
Dictionary after removing 'is_student': {'name': 'John', 'age': 31, 'city': 'New York', 'country': 'USA'}
Dictionary after popping 'city': {'name': 'John', 'age': 31, 'country': 'USA'}
Removed 'city' value: New York
Keys of the dictionary: dict_keys(['name', 'age', 'country'])
Values of the dictionary: dict_values(['John', 31, 'USA'])
Items (key-value pairs) of the dictionary: dict_items([('name', 'John'), ('age', 31), ('country', 'USA')])
Is 'name' a key in the dictionary? True
Iterating through the dictionary:
name: John
age: 31
country: USA
Dictionary after merging with another dictionary: {'name': 'John', 'age': 31, 'country': 'USA', 'gender':
'Male', 'occupation': 'Engineer'}
Copied Dictionary: {'name': 'John', 'age': 31, 'country': 'USA', 'gender': 'Male', 'occupation':
'Engineer'}
Dictionary after clearing all elements: {}

RESULT:

23
Ex no : 07 Object Creation and Usage
Date:

AIM:
To understand and implement the creation and usage of objects in an object-oriented programming (OOP)
paradigm.

ALGORITHM:

1. Start

2. Define a Class

3. Identify the attributes (variables) and behaviors (methods) that define the object.

4. Declare a class with appropriate access modifiers and methods.

5. Create a Constructor (Optional)

6. Define a constructor to initialize object attributes if necessary.

7. Create an Object

8. Instantiate an object using the new keyword (in Java, C++, etc.) or direct instantiation (in Python,
JavaScript, etc.).

9. Access and Modify Object Properties

Use dot notation (object.property or object.method()) to interact with the object.

10. Perform Operations Using Methods

11. Call object methods to perform specific actions or calculations.

12. Demonstrate Object Behavior

13. Print or manipulate object attributes to show functionality.

14. Terminate the Program

15. End

PROGRAM:

24
# ---------------------- CLASS DEFINITION ----------------------
class Person:
# Constructor (__init__ method) to initialize an object
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable

# Method to display details


def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")

# ---------------------- OBJECT CREATION ----------------------


# Creating objects of the Person class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# ---------------------- OBJECT USAGE ----------------------


# Accessing and modifying object properties
print("Before Modification:")
person1.display_info()
person2.display_info()

# Modifying object attributes


person1.age = 26

print("\nAfter Modification:")
person1.display_info() # Updated age
person2.display_info()

# Creating another object dynamically


person3 = Person("Charlie", 40)
print("\nNewly Created Object:")
person3.display_info()

OUTPUT:

Before Modification:
Name: Alice, Age: 25
Name: Bob, Age: 30

After Modification:
Name: Alice, Age: 26
Name: Bob, Age: 30

Newly Created Object:


Name: Charlie, Age: 40

25
RESULT:

26
Ex no:08 Program involving Inheritance
Date:

AIM:
To develop a Python program that demonstrates the concept of inheritance, including single, multiple, and
multilevel inheritance. The program will define a base class and derive child classes that inherit attributes and
behaviors from the parent class.

ALGORITHM:

Step 1: Define the Base Class


Create a parent class with common attributes and methods.

Use the __init__ method to initialize class attributes.

Define methods that can be inherited by child classes.

Step 2: Define the Derived (Child) Class


Create one or more child classes that inherit from the base class.

Use single inheritance (class Child(Parent):).

Implement additional attributes or override methods.

Step 3: Implement Multiple or Multilevel Inheritance (Optional)


Use multiple inheritance (class C(A, B):) to inherit from multiple parent classes.

Use multilevel inheritance (class C(B):, where B inherits from A).

Step 4: Create Objects and Test Inheritance


Instantiate objects of the child class.

Call inherited methods to verify functionality.

Override methods in the child class and check method resolution order (MRO).

Step 5: Display Results


Print attributes and method outputs to confirm successful inheritance.

Step 6: Execute the Program


Run the program and test different types of inheritance.

PROGRAM: 27
# ---------------------- BASE CLASS ----------------------
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")

# ---------------------- DERIVED CLASS (INHERITING FROM PERSON) ----------------------


class Employee(Person): # Employee inherits from Person
def __init__(self, name, age, employee_id, salary):
super().__init__(name, age) # Call the constructor of the base class
self.employee_id = employee_id
self.salary = salary

def display_employee_info(self):
self.display_info() # Call the method from the base class
print(f"Employee ID: {self.employee_id}, Salary: ${self.salary}")

# ---------------------- OBJECT CREATION & USAGE ----------------------


# Creating an object of the Employee class
employee1 = Employee("Alice", 30, "E101", 50000)

# Displaying Employee details (inherited + specific attributes)


print("Employee Details:")
employee1.display_employee_info()

OUTPUT”

Employee Details:
Name: Alice, Age: 30
Employee ID: E101, Salary: $50000

RESULT:

28
Ex no:09 Program involving Overloading
Date:

AIM:
To develop a Python program that demonstrates function overloading and operator overloading using the
special methods (__add__, __mul__, etc.) and method overloading through default arguments or @classmethod.

ALGORITHM:
Step 1: Import Required Libraries (if needed)
No external libraries are required for basic overloading.

Step 2: Define Function Overloading (Method Overloading)


In Python, method overloading is simulated using default arguments or *args.

Define a function with different argument types or numbers.

Step 3: Implement Operator Overloading


Define a class with special methods like:

__add__(self, other) → For overloading + operator

__mul__(self, other) → For overloading * operator

__str__(self) → For string representation of objects

Implement how the object behaves when operators are used.

Step 4: Create Objects and Test Overloading


Instantiate objects of the class.

Perform operations using overloaded operators (+, *, etc.).

Call the overloaded method with different arguments.

Step 5: Display the Results


Print function results to verify overloading behavior.

Step 6: Execute the Program


Run the program and test function/operator overloading.

PROGRAM:

Method Overloading Example (Using Default Arguments)

class Calculator: 29
def add(self, a, b, c=0): # Default argument allows overloading
return a + b + c

# ---------------------- OBJECT CREATION ----------------------


calc = Calculator()

# ---------------------- METHOD OVERLOADING USAGE ----------------------


print("Sum of 2 numbers:", calc.add(10, 20)) # Calls add(a, b)
print("Sum of 3 numbers:", calc.add(10, 20, 30)) # Calls add(a, b, c)

OUTPUT:

Sum of 2 numbers: 30
Sum of 3 numbers: 60

Operator Overloading Example (+ Operator Overloading)

class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other): # Overloading the `+` operator


return ComplexNumber(self.real + other.real, self.imag + other.imag)

def display(self):
print(f"{self.real} + {self.imag}i")

# ---------------------- OBJECT CREATION ----------------------


c1 = ComplexNumber(3, 5)
c2 = ComplexNumber(2, 4)

# ---------------------- OPERATOR OVERLOADING ----------------------


c3 = c1 + c2 # Uses the overloaded `__add__` method
print("Result of Addition:")
c3.display()

OUTPUT:

Result of Addition:
5 + 9i

30
RESULT:

Ex no:10 Reading and Writing with Text Files


31 and Binary Files
Date:

AIM:
To develop a Python program that demonstrates reading and writing operations with both text files and binary
files. The program will create, write, and read data from these file types to understand how data is stored and
retrieved efficiently.

ALGORITHM:
Step 1: Open and Write to a Text File
Use open("filename.txt", "w") to create and open a text file in write mode.

Write multiple lines using .write() or .writelines().

Close the file using .close() or use with open() for auto-closing.

Step 2: Read from a Text File


Use open("filename.txt", "r") to open the text file in read mode.

Read the contents using .read() (entire file), .readline() (single line), or .readlines() (list of lines).

Print the file contents.

Step 3: Open and Write to a Binary File


Use open("filename.bin", "wb") to create and open a binary file in write mode.

Write binary data using .write(b"binary data").

Close the file.

Step 4: Read from a Binary File


Use open("filename.bin", "rb") to open the file in read mode.

Read binary data using .read().

Print the binary content.

Step 5: Execute the Program


Run the program and verify that text and binary data are successfully written and read.

PROGRAM:

# ---------------------- TEXT FILE OPERATIONS ----------------------


# Writing to a text file
with open("sample.txt", "w") as text_file:
text_file.write("Hello, this is a sample text file.\n")
text_file.write("Python file handling is easy to use.\n")
32
# Reading from a text file
with open("sample.txt", "r") as text_file:
text_content = text_file.read()
print("Text File Content:\n", text_content)

# ---------------------- BINARY FILE OPERATIONS ----------------------


# Writing to a binary file
binary_data = b"This is a binary file example."
with open("sample.bin", "wb") as binary_file:
binary_file.write(binary_data)

# Reading from a binary file


with open("sample.bin", "rb") as binary_file:
binary_content = binary_file.read()
print("Binary File Content:\n", binary_content)

OUTPUT:
Text File Content:
Hello, this is a sample text file.
Python file handling is easy to use.

Binary File Content:


b'This is a binary file example.'

RESULT:

Ex no:11 Combining and Merging Data Sets


33
Date:

AIM:
To develop a Python program that demonstrates how to combine and merge datasets using the Pandas
library. The program will perform concatenation and merging of multiple datasets (CSV files, binary files) to
analyze structured data efficiently.

ALGORITHM:
Step 1: Import Required Libraries
Import pandas for handling structured data.

Import shutil (if merging binary files).

Step 2: Create Sample Datasets


Define two or more dataframes with similar or related data.

Save them as CSV files for demonstration.

Step 3: Read and Merge CSV Files


Read multiple CSV files using pd.read_csv().

Concatenate them using pd.concat() to combine row-wise.

Use pd.merge() to perform inner, left, right, or outer joins based on a common key.

Step 4: Merge Binary Files (Optional)


Open multiple binary files (.bin, images, PDFs) in rb (read binary) mode.

Append contents into a new merged file using shutil.copyfileobj().

Step 5: Save and Display the Results


Save the merged dataset as a new CSV file using to_csv().

Print the merged dataframe for verification.

If working with binary files, print confirmation of the merge.

Step 6: Execute the Program


Run the program and verify the merged output.

PROGRAM:

34
import pandas as pd

# ---------------------- CREATING SAMPLE DATA ----------------------


df1 = pd.DataFrame({
'ID': [1, 2, 3],
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
})

df2 = pd.DataFrame({
'ID': [4, 5, 6],
'Name': ['David', 'Emma', 'Frank'],
'Age': [40, 45, 50]
})

df3 = pd.DataFrame({
'ID': [2, 3, 4],
'Salary': [60000, 70000, 80000]
})

# ---------------------- CONCATENATION (COMBINING DATASETS) ----------------------


merged_df = pd.concat([df1, df2], ignore_index=True)
print("Concatenated Data:\n", merged_df)

# ---------------------- MERGING BASED ON COMMON COLUMN ----------------------


merged_on_id = pd.merge(df1, df3, on="ID", how="inner") # Inner Join
print("\nMerged Data on 'ID':\n", merged_on_id)

# ---------------------- OUTER JOIN (MERGING ALL DATA) ----------------------


merged_outer = pd.merge(df1, df3, on="ID", how="outer") # Outer Join
print("\nOuter Join Merged Data:\n", merged_outer)

OUTPUT:

Concatenated Data:
ID Name Age
0 1 Alice 25
1 2 Bob 30
2 3 Charlie 35
3 4 David 40
4 5 Emma 45
5 6 Frank 50

Merged Data on 'ID':


ID Name Age Salary
35
0 2 Bob 30 60000
1 3 Charlie 35 70000

Outer Join Merged Data:


ID Name Age Salary
0 1 Alice 25.0 NaN
1 2 Bob 30.0 60000.0
2 3 Charlie 35.0 70000.0
3 4 NaN NaN 80000.0

RESULT:

36
Ex no:12 Program involving Regular Expressions
Date:

AIM:
To develop a Python program that demonstrates the use of Regular Expressions (RegEx) for pattern matching,
searching, and text manipulation. The program will extract and validate specific patterns such as emails,
phone numbers, and URLs from a given text.

ALGORITHM:
Step 1: Import the Required Library
Import the re module to work with regular expressions.

Step 2: Define the Sample Text


Create a multiline text containing emails, phone numbers, and URLs.

Step 3: Define Regular Expression Patterns


Use regex patterns to identify:

Email addresses: [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}

Phone numbers: \+?\d{1,3}-\d{3}-\d{3}-\d{4}

URLs: https?://[a-zA-Z0-9./_-]+

Step 4: Search for Matches


Use re.findall(pattern, text) to extract matching patterns from the text.

Step 5: Display Extracted Information


Print the emails, phone numbers, and URLs found in the text.

Step 6: Perform Text Replacement (Optional)


Use re.sub(pattern, replacement, text) to replace sensitive information (e.g., emails) with
placeholders like [REDACTED].

Step 7: Execute the Program


Run the program and verify the output.

PROGRAM:

import re

# Sample text for pattern matching


text = """
Hello, my name is Alice. My email is alice123@example.com.
37
You can also contact Bob at bob_456@test.org.
My phone number is +1-987-654-3210.
Visit https://www.example.com for more details.
"""

# ---------------------- REGULAR EXPRESSION PATTERNS ----------------------


email_pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
phone_pattern = r"\+?\d{1,3}-\d{3}-\d{3}-\d{4}"
url_pattern = r"https?://[a-zA-Z0-9./_-]+"

# ---------------------- SEARCHING USING REGEX ----------------------


emails = re.findall(email_pattern, text)
phones = re.findall(phone_pattern, text)
urls = re.findall(url_pattern, text)

# ---------------------- OUTPUT RESULTS ----------------------


print("Extracted Emails:", emails)
print("Extracted Phone Numbers:", phones)
print("Extracted URLs:", urls)

# ---------------------- REPLACING TEXT USING REGEX ----------------------


censored_text = re.sub(email_pattern, "[REDACTED EMAIL]", text)
print("\nCensored Text:\n", censored_text)

OUTPUT:

Extracted Emails: ['alice123@example.com', 'bob_456@test.org']


Extracted Phone Numbers: ['+1-987-654-3210']
Extracted URLs: ['https://www.example.com']

Censored Text:
Hello, my name is Alice. My email is [REDACTED EMAIL].
You can also contact Bob at [REDACTED EMAIL].
My phone number is +1-987-654-3210.
Visit https://www.example.com for more details.

RESULT:

Ex no:13 Data Aggregation and GroupWise Operations


38
Date:

AIM:
To develop a Python program that performs Data Aggregation and Group-wise Operations using Pandas.
The program will demonstrate how to compute summary statistics (e.g., sum, mean, max) and perform group-wise
aggregations on a dataset.

ALGORITHM:
Step 1: Import Required Libraries
Import the pandas library to handle data operations.

Step 2: Create a Sample Dataset


Define a dictionary with data fields such as Department, Employee, Salary, and Experience.

Convert the dictionary into a Pandas DataFrame.

Step 3: Perform Data Aggregation


Compute sum, mean, max, and min of the Salary column.

Step 4: Perform Group-wise Operations


Use groupby() to categorize data by Department.

Apply aggregation functions such as:

sum() for total salary

mean() for average salary

count() for employee count

max() for highest experience in each department

Step 5: Find the Highest Paid Employee in Each Department


Use groupby("Department")["Salary"].idxmax() to get the highest-paid employee for each
department.

Step 6: Display the Results


Print the aggregated and group-wise results.

PROGRAM:

39
import pandas as pd

# ---------------------- SAMPLE DATA CREATION ----------------------


# Creating a DataFrame with Employee Salary Data
data = {
'Department': ['HR', 'IT', 'HR', 'Finance', 'IT', 'Finance', 'HR', 'IT'],
'Employee': ['Alice', 'Bob', 'Charlie', 'David', 'Emma', 'Frank', 'Grace', 'Hannah'],
'Salary': [50000, 70000, 60000, 80000, 75000, 82000, 55000, 72000],
'Experience': [5, 8, 6, 10, 9, 12, 4, 7]
}

df = pd.DataFrame(data)
print("Original Data:\n", df)

# ---------------------- DATA AGGREGATION ----------------------


# Aggregate functions applied to the entire dataset
total_salary = df['Salary'].sum()
average_salary = df['Salary'].mean()
max_salary = df['Salary'].max()
min_salary = df['Salary'].min()

print("\nTotal Salary Expense:", total_salary)


print("Average Salary:", average_salary)
print("Maximum Salary:", max_salary)
print("Minimum Salary:", min_salary)

# ---------------------- GROUP-WISE OPERATIONS ----------------------


# Grouping by 'Department' and applying aggregation functions
grouped_df = df.groupby('Department').agg(
Total_Salary=('Salary', 'sum'),
Average_Salary=('Salary', 'mean'),
Employee_Count=('Employee', 'count'),
Max_Experience=('Experience', 'max')
)

print("\nGroup-wise Aggregation by Department:\n", grouped_df)

# ---------------------- ADVANCED GROUP-BY OPERATION ----------------------


# Finding the highest-paid employee in each department
highest_paid = df.loc[df.groupby("Department")["Salary"].idxmax(), ["Department", "Employee", "Salary"]]
print("\nHighest Paid Employee in Each Department:\n", highest_paid)

OUTPUT:
40
Original Data:
Department Employee Salary Experience
0 HR Alice 50000 5
1 IT Bob 70000 8
2 HR Charlie 60000 6
3 Finance David 80000 10
4 IT Emma 75000 9
5 Finance Frank 82000 12
6 HR Grace 55000 4
7 IT Hannah 72000 7

Total Salary Expense: 544000


Average Salary: 68000.0
Maximum Salary: 82000
Minimum Salary: 50000

Group-wise Aggregation by Department:


Total_Salary Average_Salary Employee_Count Max_Experience
Department
Finance 162000 81000 2 12
HR 165000 55000 3 6
IT 217000 72333 3 9

Highest Paid Employee in Each Department:


Department Employee Salary
3 Finance Frank 82000
2 HR Charlie 60000
4 IT Emma 75000

RESULT:

41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy