data science
data science
STUDENT NAME :
CLASS :
REGISTER NUMBER :
SEMESTER :
DHANALAKSHMI SRINIVASAN ARTS AND SCIENCE (Co-Education) COLLEGE
(Affiliated to University of Madras)
REGISTER NUMBER :
SUBJECT CODE :
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:
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")
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.")
if __name__ == "__main__":
flow_control_program()
OUTPUT:
Welcome to the Flow Control Program!
You can choose different flow control options to execute the program.
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.
10. End
PROGRAM:
8
def subtract(a, b):
"""Function to subtract b from a."""
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")
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)}")
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.
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:
1. Start
2. Open a text file in the required mode (read, write, append, etc.).
3. Perform operations:
6. End
1. Start
2. Open a binary file in the required mode (rb for reading, wb for writing, ab for appending).
3. Perform operations:
8. End
12
Program:
def string_manipulation():
# Sample string for manipulation
original_string = "Hello, Python Programming!"
# 1. String Length
# 2. String to Uppercase
print(f"Uppercase: {original_string.upper()}")
# 3. String to Lowercase
print(f"Lowercase: {original_string.lower()}")
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}")
# 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}")
Output:
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
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}")
# 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}")
# 6. Removing an element
my_list.remove("Python")
print(f"List after removing 'Python': {my_list}")
Output:
RESULT:
20
Ex no:06 Creating and manipulating a Dictionary
Date:
AIM:
ALGORITHM:
1. Start
2. Create a Dictionary
13. Get all keys, values, or items, check for the existence of a key, iterate through the dictionary,
etc.
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}")
# 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}")
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.
7. Create an Object
8. Instantiate an object using the new keyword (in Java, C++, etc.) or direct instantiation (in Python,
JavaScript, etc.).
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
print("\nAfter Modification:")
person1.display_info() # Updated age
person2.display_info()
OUTPUT:
Before Modification:
Name: Alice, Age: 25
Name: Bob, Age: 30
After Modification:
Name: Alice, Age: 26
Name: Bob, Age: 30
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:
Override methods in the child class and check method resolution order (MRO).
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}")
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}")
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.
PROGRAM:
class Calculator: 29
def add(self, a, b, c=0): # Default argument allows overloading
return a + b + c
OUTPUT:
Sum of 2 numbers: 30
Sum of 3 numbers: 60
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def display(self):
print(f"{self.real} + {self.imag}i")
OUTPUT:
Result of Addition:
5 + 9i
30
RESULT:
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.
Close the file using .close() or use with open() for auto-closing.
Read the contents using .read() (entire file), .readline() (single line), or .readlines() (list of lines).
PROGRAM:
OUTPUT:
Text File Content:
Hello, this is a sample text file.
Python file handling is easy to use.
RESULT:
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.
Use pd.merge() to perform inner, left, right, or outer joins based on a common key.
PROGRAM:
34
import pandas as pd
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]
})
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
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.
URLs: https?://[a-zA-Z0-9./_-]+
PROGRAM:
import re
OUTPUT:
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:
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.
PROGRAM:
39
import pandas as pd
df = pd.DataFrame(data)
print("Original Data:\n", df)
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
RESULT:
41