You are on page 1of 31

Practical No:-2

Program for understanding the data types, control flow statement, block and loops.

# Data types

number = 10

floating_point = 3.14

text = "Hello, World!"

is_true = True

is_false = False

my_list = [1, 2, 3, 4, 5]

my_tuple = (1, 2, 3)

my_set = {1, 2, 3}

my_dictionary = {"name": "John", "age": 30}

# Control flow statements

if number > 5:

print("Number is greater than 5.")

else:

print("Number is less than or equal to 5.")

for item in my_list:

print(item)

i=0
while i < 5:

print("Value of i:", i)

i += 1

# Block indentation

if is_true:

print("It is true.")

print("Still inside the block.")

print("Outside the block.")

# Main program

def main():

print(text)

if __name__ == "__main__":

main()
Practical No:-3

Program for understanding function,use of built in function, user defined functions.

# Built-in function example

text = "hello, world!"

uppercase_text = text.upper()

print(uppercase_text)

# User-defined function example

def add_numbers(a, b):

return a + b

result = add_numbers(5, 10)

print("Sum:", result)
Practical No:-4

Program to use existing module, packages and creating modules, packeges.

# Using existing module packages

import math

import random

# Using math module

print("Square root of 16:", math.sqrt(16))

print("Value of pi:", math.pi)

# Using random module

random_num = random.randint(1, 100)

print("Random number between 1 and 100:", random_num)

____________________________________________________________________

- mypackage

- module1.py

- module2.py

- main.py

____________________________________________________________________

**********Module 1**********

def greet(name):
print("Hello, " + name + "! Welcome to Module 1.")

____________________________________________________________________

****************Module2********

def calculate_sum(a, b):

return a + b

____________________________________________________________________

****************Main.py**************

from mypackage import module1, module2

module1.greet("John")

result = module2.calculate_sum(5, 10)

print("Sum:", result)
Practical No:-5

Program for implementations of all OOPs concept like class


,method,inheritance,polymorphism. Etc.

class Shape:

def __init__(self, color):

self.color = color

def area(self):

pass

def display(self):

print(f"Color: {self.color}")

# Child class (inheritance)

class Rectangle(Shape):

def __init__(self, color, width, height):

super().__init__(color)

self.width = width

self.height = height

# Method overriding
def area(self):

return self.width * self.height

# Child class (inheritance)

class Circle(Shape):

def __init__(self, color, radius):

super().__init__(color)

self.radius = radius

# Method overriding

def area(self):

return 3.14 * self.radius * self.radius

# Polymorphism

def calculate_area(shape):

if isinstance(shape, Shape):

return shape.area()

else:

return "Invalid shape."

# Main program
def main():

# Create instances of the classes

rectangle = Rectangle("Red", 5, 10)

circle = Circle("Blue", 3)

# Display shapes' properties

rectangle.display()

print("Rectangle area:", calculate_area(rectangle))

circle.display()

print("Circle area:", calculate_area(circle))

if __name__ == "__main__":

main()
Practical No:-6

Program for parsing of data , validation like password ,email,url,etc.

import re

# Password validation

def validate_password(password):

# Minimum 8 characters, at least one uppercase letter, one lowercase letter, one digit,
and one special character

pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"

if re.match(pattern, password):

print("Valid password.")

else:

print("Invalid password.")

# Email validation

def validate_email(email):

# Basic email format validation

pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"

if re.match(pattern, email):

print("Valid email.")

else:

print("Invalid email.")
# URL validation

def validate_url(url):

# Basic URL format validation

pattern = r"^(http|https)://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"

if re.match(pattern, url):

print("Valid URL.")

else:

print("Invalid URL.")

# Main program

def main():

# Password validation

password = "Abc@12345"

validate_password(password)

# Email validation

email = "test@example.com"

validate_email(email)

# URL validation

url = "https://www.example.com"

validate_url(url)

if __name__ == "__main__":

main()
Practical No:-7

Program for pattern finding should be covered.

import re

def find_pattern(text, pattern):

matches = re.findall(pattern, text)

if matches:

print("Pattern found:", matches)

else:

print("Pattern not found.")

# Main program

def main():

text = "The quick brown fox jumps over the lazy dog."

pattern = r'\b\w{5}\b' # Find 5-letter words

find_pattern(text, pattern)

if __name__ == "__main__":

main()
Practical No:-8

Program covering all aspects of Exception handling , user defined exception


,multithreading should be covered.

import threading

# User-defined Exception

class CustomException(Exception):

def __init__(self, message):

self.message = message

# Exception Handling

def perform_division(a, b):

try:

result = a / b

print("Division result:", result)

except ZeroDivisionError:

print("Error: Division by zero!")

except Exception as e:

print("Error:", e)

# Threading

def print_numbers():
for i in range(1, 6):

print("Printing from thread 1:", i)

def print_letters():

for letter in 'ABCDE':

print("Printing from thread 2:", letter)

# Main program

def main():

# Exception Handling

perform_division(10, 2)

perform_division(10, 0)

perform_division(10, '2')

# User-defined Exception

try:

raise CustomException("Custom Exception raised!")

except CustomException as ce:

print("Custom Exception caught:", ce.message)

# Threading

thread1 = threading.Thread(target=print_numbers)

thread2 = threading.Thread(target=print_letters)
thread1.start()

thread2.start()

thread1.join()

thread2.join()

if __name__ == "__main__":

main()
Practical No:-9

Program to demonstrating IO operation like reading from file, writing into file from
different file type like data file,binary file etc.

# Read from data file

def read_data_file(file_path):

with open(file_path, 'r') as file:

data = file.read()

print("Data from data file:")

print(data)

# Write to text file

def write_to_text_file(file_path, content):

with open(file_path, 'w') as file:

file.write(content)

print("Content written to text file.")

# Write to binary file

def write_to_binary_file(file_path, data):

with open(file_path, 'wb') as file:

file.write(data)

print("Data written to binary file.")

# Main program
def main():

# Read from data file

data_file_path = 'data.txt' # Replace with your data file path

read_data_file(data_file_path)

# Write to text file

text_file_path = 'output.txt' # Replace with your text file path

content = "This is some text content."

write_to_text_file(text_file_path, content

# Write to binary file

binary_file_path = 'output.bin' # Replace with your binary file path

data = b'\x48\x65\x6c\x6c\x6f' # Example binary data

write_to_binary_file(binary_file_path, data)

if __name__ == "__main__":

main()
Practical No:-10

Program to performsearching, adding, updating the content from file.

def search_content(file_path, search_query):

with open(file_path, 'r') as file:

lines = file.readlines()

for line in lines:

if search_query in line:

print(line.strip())

def add_content(file_path, new_content):

with open(file_path, 'a') as file:

file.write(new_content + '\n')

print("Content added successfully.")

def update_content(file_path, search_query, new_content):

with open(file_path, 'r') as file:

lines = file.readlines()

with open(file_path, 'w') as file:

for line in lines:

if search_query in line:

file.write(new_content + '\n')

else:

file.write(line)

print("Content updated successfully.")


# Main program

def main():

file_path = 'data.txt' # Replace with your file path

# Search content

search_query = 'example'

search_content(file_path, search_query)

# Add content

new_content = 'New line added'

add_content(file_path, new_content)

# Update content

search_query = 'example'

new_content = 'Line updated'

update_content(file_path, search_query, new_content)

# Search updated content

search_query = 'example'

search_content(file_path, search_query)

if __name__ == "__main__":
Practical No:-11

Program for performing CRUD operation with mongoDB and python.

from pymongo import MongoClient

# Connect to MongoDB

client = MongoClient('mongodb://localhost:27017/')

db = client['mydatabase'] # Replace 'mydatabase' with your desired database name

collection = db['mycollection'] # Replace 'mycollection' with your desired collection


name

# Create operation

def create_document(data):

result = collection.insert_one(data)

print("Document inserted. ID:", result.inserted_id)

# Read operation

def read_documents():

documents = collection.find()

for doc in documents:

print(doc)

# Update operation

def update_document(query, update_data):


result = collection.update_one(query, {'$set': update_data})

print("Document updated. Modified count:", result.modified_count)

# Delete operation

def delete_document(query):

result = collection.delete_one(query)

print("Document deleted. Deleted count:", result.deleted_count)

# Main program

def main():

# Create operation

data = {

'name': 'John',

'age': 30,

'city': 'New York'

create_document(data)

# Read operation

read_documents()

# Update operation

query = {'name': 'John'}

update_data = {'age': 31}


update_document(query, update_data)

# Read operation

read_documents()

# Delete operation

query = {'name': 'John'}

delete_document(query)

# Read operation

read_documents()

if __name__ == "__main__":

main()
Practical No:-12

Basic program performing with Numpy as Array ,searching and sorting ,date and time
and string handling.

import numpy as np

# Searching in NumPy array

def search_array():

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

target = 3

index = np.where(arr == target)

if len(index[0]) > 0:

print(f"Element {target} found at index {index[0][0]}")

else:

print(f"Element {target} not found")

# Sorting date and time

def sort_dates():

dates = np.array(['2022-01-01', '2021-12-31', '2022-01-05', '2022-01-03'])

sorted_dates = np.sort(dates)

print(f"Sorted dates: {sorted_dates}")

# String handling

def string_handling():
string = "Hello, World!"

upper = np.char.upper(string)

lower = np.char.lower(string)

print(f"Uppercase: {upper}")

print(f"Lowercase: {lower}")

# Main program

def main():

search_array()

sort_dates()

string_handling()

if __name__ == "__main__":

main()
Practical No:-13

Program for series and data frames should be covered.

import pandas as pd

# Creating a Series

def create_series():

data = [10, 20, 30, 40, 50]

s = pd.Series(data)

print("Series:")

print(s)

# Creating a DataFrame

def create_dataframe():

data = {'Name': ['John', 'Emma', 'Peter', 'Lisa'],

'Age': [25, 30, 35, 40],

'City': ['New York', 'Paris', 'London', 'Sydney']}

df = pd.DataFrame(data)

print("\nDataFrame:")

print(df)

# Accessing data in Series

def access_series():

data = [10, 20, 30, 40, 50]


s = pd.Series(data)

print("\nAccessing data in Series:")

print("Element at index 2:", s[2])

print("Elements at indexes 1 and 3:", s[[1, 3]])

print("Elements with values greater than 30:", s[s > 30])

# Accessing data in DataFrame

def access_dataframe():

data = {'Name': ['John', 'Emma', 'Peter', 'Lisa'],

'Age': [25, 30, 35, 40],

'City': ['New York', 'Paris', 'London', 'Sydney']}

df = pd.DataFrame(data)

print("\nAccessing data in DataFrame:")

print("Column 'Name':", df['Name'])

print("Row at index 2:")

print(df.loc[2])

print("Subset of DataFrame:")

print(df[['Name', 'Age']])

# Main program

def main():

create_series()

create_dataframe()

access_series()
access_dataframe()

if __name__ == "__main__":

main()
Practical No:-14

Program to demonstrate data preprocessing and dada handling with dataframe

import pandas as pd

# Data preprocessing

def preprocess_data():

# Load data from CSV file

df = pd.read_csv('data.csv')

# Drop missing values

df = df.dropna()

# Remove duplicates

df = df.drop_duplicates()

# Normalize data

df['age'] = (df['age'] - df['age'].mean()) / df['age'].std()

# Convert categorical variables to numerical

df['gender'] = df['gender'].map({'Male': 0, 'Female': 1})

return df
# Data handling

def handle_data(df):

# Filtering data

filtered_df = df[df['age'] > 30]

# Sorting data

sorted_df = df.sort_values('age', ascending=False)

# Grouping data

grouped_df = df.groupby('gender')['income'].mean()

# Output results

print("Filtered Data:")

print(filtered_df)

print("\nSorted Data:")

print(sorted_df)

print("\nGrouped Data:")

print(grouped_df)

# Main program

def main():

# Preprocess data
df = preprocess_data()

# Handle data

handle_data(df)

if __name__ == "__main__":

main()
Practical No:-15

Program fir data visualization should be covered.

import matplotlib.pyplot as plt

import pandas as pd

# Data visualization

def visualize_data():

# Load data from CSV file

df = pd.read_csv('data.csv')

# Bar chart

plt.figure(figsize=(8, 6))

plt.bar(df['Name'], df['Sales'])

plt.xlabel('Name')

plt.ylabel('Sales')

plt.title('Sales by Name')

plt.xticks(rotation=45)

plt.show()

# Line chart

plt.figure(figsize=(8, 6))

plt.plot(df['Year'], df['Revenue'], marker='o')

plt.xlabel('Year')
plt.ylabel('Revenue')

plt.title('Revenue Over Years')

plt.grid(True)

plt.show()

# Scatter plot

plt.figure(figsize=(8, 6))

plt.scatter(df['Age'], df['Salary'], c=df['Performance'], cmap='viridis')

plt.xlabel('Age')

plt.ylabel('Salary')

plt.title('Age vs Salary (Performance)')

plt.colorbar(label='Performance')

plt.show()

# Main program

def main():

visualize_data()

if __name__ == "__main__":

main()

You might also like