Department of Information and Technology
SESSION : 24-25
PRACTICAL FILE
NAME OF SUBJECT : PYTHON
NAME OF STUDENT : Lucky nikule
ENROLLMENT NO :
INDEX
SR. NO NAME OF PRACTICAL
1 Practical No. 1: Install Python IDE
2 Practical No. 2: Write a simple Python program to
display a message on the screen
3 Practical No. 3: Write a simple Python program using operators:
Arithmetic Operators, Logical Operators, Bitwise Operators.
4 Practical No. 4: Write a simple Python program to demonstrate
the use of conditional statements: if’ statement, ‘if … else’
statement, and Nested ‘if’ statement.
5 Practical No. 5: Write a Python program to demonstrate the use
of looping statements: ‘while’ loop, ‘for’ loop, and Nested loop.
6 Practical No. 6: Write a Python program to demonstrate the use
of loop control statements: continue, pass, break.
7 Practical No. 7: Write a Python program to perform the following
operations on Lists: Create list, access list, Update list (Add item,
remove item), and delete list.
Practical No. 8: Write a Python program to use built-in functions/methods
8 on the list: cmp, len, max, list, append, count, extend, insert, pop, remove,
etc
Practical No. 9: Write a Python program to perform the following
9 operations on a tuple: Create, Access, Print, Delete & Convert the tuple into
a list, and vice versa.
10 Practical No. 10: Create set, Access Set, Update Set, Delete Set.
Practical No. 11: Write a Python program to perform the following
11 functions on Set: Union, Intersection, Difference, Symmetric Difference.
*Implement a python program to perform following
12
operations on the Dictionary:
1. Create a Dictionary
2. Access Dictionary
3. Update Dictionary
4. Delete Dictionary
5. Looping through Dictionary
6. Create Dictionary from list
Practical No. 13: Write a user-defined function to implement the following
13 features: Function without argument, Function with argument, Function
returning value.
Practical No. 14
14
Write a user Define Function to Implement for following Problem: Function
Positional/Required Argument, Function with keyword argument, Function
with default argument, Function with variable length argument
Practical No. 15: Write Python program to demonstrate use of following
15 advanced functions: lambda, map, reduce
Practical No. 16: Write a python program to create and use a user defined
16 module for a given problem
Practical No. 17: Write a python program to demonstrate the use of
17 following module: 1. Math module 2. Random module 3. OS module
Practical No. 18: Write python program to create and use a user defined
18 package for a given problem
Practical No. 19: Write a python program to use of numpy package to
19 perform operation on 2D matrix. Write a python program to use of
matplotlib package to represent data in graphical form
Practical No. 20: Develop a python program to perform following operations:
20 1. Creating a Class with method 2. Creating Objects of class 3. Accessing
method using
Practical No. 21: Write a python program to demonstrate the use of
21 constructors: 1. Default 2. Parameterized 3. Constructor
Practical No. 22: Implement a Python Program to Demonstrate 1. Method
22 Overloading
2. Method Overriding
Practical No. 23: Write Python Program to Demonstrate
23
Data Hiding
Practical No. 24: Write a python program to implement 1. Single inheritance
24 2. Multiple Inheritance 3. Multilevel inheritance
Practical No 25: Implement Python program to perform following operations
25 using panda package:
1 . Create Series from Array 2. Create Series from List
3. Access element of series 4. Create DataFrame using List or dictionary
Practical No. 26: Implement Python Program to Load a CSV file into a Pandas
26 DataFrame and Perform Operations.
Practical No. 27: Write python GUI program to import Tkinter package and
27 create a window and set its title
Practical No. 28: Write Python GUI Program that Adds Labels and Buttons to
28 the Tkinter Window
Practical No. 29: Write program to create a connection between database
29 and python
Practical No. 30: Implement Python Program to Select Records from the
30
Database Table and Display the Result
Name of Faculty & Sign HOD
SIGN
Practical No. 1: Install Python IDE
Step 1: Choose a Python IDE
Here are a few popular options:
● PyCharm (feature-rich and excellent for complex projects)
● Visual Studio Code (VS Code) (lightweight and customizable)
● Jupyter Notebook (interactive, great for data science)
● IDLE (simple and comes with Python by default)
Step 2: Download the IDE
● Visit the official website of the IDE you've chosen (e.g., PyCharm or VS Code).
● Download the appropriate version for your operating system (Windows, macOS,
Linux).
Step 3: Install the IDE
● Run the downloaded installer file and follow the on-screen instructions.
● For VS Code, you may also want to install the Python extension for added features.
Step 4: Set Up Python (if not already installed)
● Download Python from python.org.
● During installation, check the box to “Add Python to PATH.”
Practical No. 2: Write a simple Python program to display a
message on the screen
PROGRAM NO. 1
print("Hello, world!")
print()
print("I am a student in the 2nd year of Polytechnic.")
OUTPUT
Hello, world!
I am a student in the 2nd year of Polytechnic.
Process finished with exit code 0
Practical No. 3: Write a simple Python program using operators: Arithmetic
Operators, Logical Operators, Bitwise Operators.
# Program using different types of operators
# Arithmetic Operators
num1 = 10
num2 = 5
print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
print("Division:", num1 / num2)
# Logical Operators
x = True
y = False
print("Logical AND:", x and y) # True only if both are True
print("Logical OR:", x or y) # True if either is True
print("Logical NOT:", not x) # Reverses the truth value
# Bitwise Operators
a = 4 # Binary: 100
b = 2 # Binary: 010
print("Bitwise AND:", a & b) # Result: 000 (Binary AND)
print("Bitwise OR:", a | b) # Result: 110 (Binary OR)
print("Bitwise XOR:", a ^ b) # Result: 110 (Binary XOR)
print("Bitwise NOT:", ~a) # Result: Inverted bits
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Logical AND: False
Logical OR: True
Logical NOT: False
Bitwise AND: 0
Bitwise OR: 6
Bitwise XOR: 6
Bitwise NOT: -5
Process finished with exit code 0
Practical No. 4: Write a simple Python program to demonstrate the use of
conditional statements: if’ statement, ‘if … else’ statement, and Nested ‘if’
statement.
# Program to demonstrate conditional statements
# Example of 'if' statement
number = 5
if number > 0:
print("The number is positive.")
# Example of 'if...else' statement
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
# Example of nested 'if' statements
marks = 85
if marks >= 50:
print("You passed the exam.")
if marks >= 90:
print("You scored an A grade.")
elif marks >= 75:
print("You scored a B grade.")
else:
print("You scored a C grade.")
else:
print("You failed the exam.")
OUTPUT
The number is positive.
You are eligible to vote.
You passed the exam.
You scored a B grade.
Process finished with exit code 0
Practical No. 5: Write a Python program to demonstrate the use of looping
statements: ‘while’ loop, ‘for’ loop, and Nested loop.
# Program to demonstrate looping statements
# 'while' loop example
count = 1
print("Using 'while' loop:")
while count <= 5:
print("Count is:", count)
count += 1 # Increment the counter
# 'for' loop example
print("\nUsing 'for' loop:")
for num in range(1, 6): # Loop from 1 to 5
print("Number is:", num)
# Nested loop example
print("\nUsing nested loops:")
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"i={i}, j={j}") # Display combination of i and j
OUTPUT
Using 'while' loop:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Using 'for' loop:
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
Using nested loops:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
Process finished with exit code 0
Practical No. 6: Write a Python program to demonstrate the use of loop
control statements: continue, pass, break.
# Program to demonstrate loop control statements
# 'continue' statement example
print("Using 'continue':")
for i in range(1, 6):
if i == 3:
continue # Skip the rest of the loop when i is 3
print("Number:", i)
# 'pass' statement example
print("\nUsing 'pass':")
for i in range(1, 6):
if i == 3:
pass # Does nothing, just a placeholder
print("Number:", i)
# 'break' statement example
print("\nUsing 'break':")
for i in range(1, 6):
if i == 3:
break # Exit the loop when i is 3
print("Number:", i)
OUTPUT
Using 'continue':
Number: 1
Number: 2
Number: 4
Number: 5
Using 'pass':
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Using 'break':
Number: 1
Number: 2
Process finished with exit code 0
Practical No. 7: Write a Python program to perform the following operations
on Lists: Create list, access list, Update list (Add item, remove item), and
delete list.
# Program to demonstrate operations on lists
# 1. Create a list
my_list = ["apple", "banana", "cherry"]
print("Created List:", my_list)
# 2. Access elements in the list
print("\nAccessing elements:")
print("First element:", my_list[0]) # Accessing the first element
print("Last element:", my_list[-1]) # Accessing the last element
# 3. Update the list
print("\nUpdating the list:")
# Add an item
my_list.append("orange")
print("List after adding an item:", my_list)
# Remove an item
my_list.remove("banana")
print("List after removing an item:", my_list)
# 4. Delete the list
print("\nDeleting the list:")
del my_list # Deleting the entire list
# Attempting to print the list after deletion will result in an error
print("The list has been deleted.")
OUTPUT
Created List: ['apple', 'banana', 'cherry']
Accessing elements:
First element: apple
Last element: cherry
Updating the list:
List after adding an item: ['apple', 'banana', 'cherry', 'orange']
List after removing an item: ['apple', 'cherry', 'orange']
Deleting the list:
The list has been deleted.
Process finished with exit code 0
Practical No. 8: Write a Python program to use built-in
functions/methods on the list: cmp, len, max, list, append, count,
extend, insert, pop, remove, etc
# Initial list
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)
# 1. Using len() to find the length of the list
length = len(my_list)
print("Length of the list:", length)
# 2. Using max() to find the maximum value in the list
maximum = max(my_list)
print("Maximum value in the list:", maximum)
# 3. Using list() to create a new list
new_list = list((60, 70, 80))
print("New List created using list():", new_list)
# 4. Using append() to add an element to the list
my_list.append(60)
print("List after appending 60:", my_list)
# 5. Using count() to count the occurrences of an element
count = my_list.count(20)
print("Count of 20 in the list:", count)
# 6. Using extend() to extend the list with another list
my_list.extend([70, 80, 90])
print("List after extending with [70, 80, 90]:", my_list)
# 7. Using insert() to insert an element at a specific position
my_list.insert(2, 25)
print("List after inserting 25 at index 2:", my_list)
# 8. Using pop() to remove and return an element
popped_element = my_list.pop(3)
print("Popped element:", popped_element)
print("List after popping element at index 3:", my_list)
# 9. Using remove() to safely remove an element (check if it exists first)
if 30 in my_list:
my_list.remove(30)
print("List after removing 30:", my_list)
else:
print("Element 30 not found in the list, skipping remove operation.")
# Final result
print("Final List:", my_list)
OUTPUT
Original List: [10, 20, 30, 40, 50]
Length of the list: 5
Maximum value in the list: 50
New List created using list(): [60, 70, 80]
List after appending 60: [10, 20, 30, 40, 50, 60]
Count of 20 in the list: 1
List after extending with [70, 80, 90]: [10, 20, 30, 40, 50, 60, 70, 80, 90]
List after inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60, 70, 80, 90]
Popped element: 30
List after popping element at index 3: [10, 20, 25, 40, 50, 60, 70, 80, 90]
Element 30 not found in the list, skipping remove operation.
Final List: [10, 20, 25, 40, 50, 60, 70, 80, 90]
Process finished with exit code 0
Practical No. 9: Write a Python program to perform the following operations
on a tuple: Create, Access, Print, Delete & Convert the tuple into a list, and
vice versa.
# 1. Create a tuple
my_tuple = (10, 20, 30, 40, 50)
print("Created Tuple:", my_tuple)
# 2. Access elements of the tuple
print("Accessing elements:")
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
print("Slice (elements from index 1 to 3):", my_tuple[1:4])
# 3. Print the tuple
print("Printing the Tuple:", my_tuple)
# 4. Delete the tuple
# Note: Tuples are immutable, so we cannot delete individual elements.
# But we can delete the entire tuple.
del my_tuple
print("Tuple deleted!") # This will cause an error if you try to access `my_tuple` after
deletion.
# 5. Convert the tuple into a list
my_tuple = (60, 70, 80, 90, 100) # Recreating the tuple for demonstration
my_list = list(my_tuple)
print("Converted Tuple into List:", my_list)
# 6. Convert the list back into a tuple
new_tuple = tuple(my_list)
print("Converted List back into Tuple:", new_tuple)
OUTPUT
Created Tuple: (10, 20, 30, 40, 50)
Accessing elements:
First element: 10
Last element: 50
Slice (elements from index 1 to 3): (20, 30, 40)
Printing the Tuple: (10, 20, 30, 40, 50)
Tuple deleted!
Converted Tuple into List: [60, 70, 80, 90, 100]
Converted List back into Tuple: (60, 70, 80, 90, 100)
Process finished with exit code 0
Practical No. 10: Create set, Access Set, Update Set, Delete Set.
# 1. Create a set
my_set = {10, 20, 30, 40, 50}
print("Created Set:", my_set)
# 2. Access elements of the set
# Note: Sets are unordered, so you cannot access elements using an index.
# However, you can loop through the set to access its elements.
print("Accessing elements:")
for element in my_set:
print(element, end=" ")
print()
# 3. Update the set
# Adding an element to the set
my_set.add(60)
print("Set after adding 60:", my_set)
# Adding multiple elements to the set
my_set.update([70, 80, 90])
print("Set after adding [70, 80, 90]:", my_set)
# Removing an element (safe method)
my_set.discard(20)
print("Set after discarding 20 (if present):", my_set)
# Removing an element (raises error if not present)
my_set.remove(30) # Be cautious, as it raises KeyError if element is absent
print("Set after removing 30:", my_set)
# 4. Delete the set
del my_set
print("Set deleted!")
OUTPUT
Created Set: {50, 20, 40, 10, 30}
Accessing elements:
50 20 40 10 30
Set after adding 60: {50, 20, 40, 10, 60, 30}
Set after adding [70, 80, 90]: {70, 10, 80, 20, 90, 30, 40, 50, 60}
Set after discarding 20 (if present): {70, 10, 80, 90, 30, 40, 50, 60}
Set after removing 30: {70, 10, 80, 90, 40, 50, 60}
Set deleted!
Process finished with exit code 0
Practical No. 11: Write a Python program to perform the following functions
on Set: Union, Intersection, Difference, Symmetric Difference2 = {4, 5, 6, 7, 8}
# Perform set operations
union_set = set1.union(set2) # Union
intersection_set = set1.intersection(set2) # Intersection
difference_set = set1.difference(set2) # Difference (elements in set1 but not in
set2)
symmetric_difference_set = set1.symmetric_difference(set2) # Symmetric
Difference
# Display results
print("Set 1:", set1)
print("Set 2:", set2)
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference (Set1 - Set2):", difference_set)
print("Symmetric Difference:", symmetric_difference_set)
OUTPUT
Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (Set1 - Set2): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Practical No. 12: Write a Python program to perform the following operations
on the Dictionary: Create, Access, Update, Delete, Looping through the
Dictionary, and Create a Dictionary from the list.
# Creating a dictionary
student_info = {"name": "Alice", "age": 20, "course": "Computer Science"}
print("Initial Dictionary:", student_info)
# Accessing values in a dictionary
print("Name:", student_info["name"]) # Accessing value by key
# Updating a dictionary
student_info["age"] = 21 # Updating an existing key
student_info["grade"] = "A" # Adding a new key-value pair
print("Updated Dictionary:", student_info)
# Deleting items in a dictionary
del student_info["course"] # Deleting a key-value pair
print("Dictionary after deletion:", student_info)
# Looping through the dictionary
print("Dictionary items:")
for key, value in student_info.items():
print(f"{key}: {value}")
# Creating a dictionary from a list
keys = ["name", "age", "grade"]
values = ["Bob", 22, "B"]
new_dict = dict(zip(keys, values))
print("Dictionary from List:", new_dict)
OUTPUT
Initial Dictionary: {'name': 'Alice', 'age': 20, 'course': 'Computer Science'}
Name: Alice
Updated Dictionary: {'name': 'Alice', 'age': 21, 'course': 'Computer Science',
'grade': 'A'}
Dictionary after deletion: {'name': 'Alice', 'age': 21, 'grade': 'A'}
Dictionary items:
name: Alice
age: 21
grade: A
Dictionary from List: {'name': 'Bob', 'age': 22, 'grade': 'B'}
Process finished with exit code 0
Practical No. 13: Write a user-defined function to implement the
following features: Function without argument, Function with
argument, Function returning value.
# Function without argument
def greet():
print("Hello! Welcome to Python programming.")
# Function with argument
def greet_person(name):
print(f"Hello, {name}! Welcome to Python programming.")
# Function returning value
def add_numbers(a, b):
return a + b
# Calling the functions
greet() # Calls function without argument
greet_person("Alice") # Calls function with argument
result = add_numbers(5, 3) # Calls function returning value
print("Sum:", result)
OUTPUT
Hello! Welcome to Python programming.
Hello, Alice! Welcome to Python programming.
Sum: 8
Process finished with exit code 0
Practical No. 14 Write a user Define Function to Implement for
following Problem: Function Positional/Required Argument,
Function with keyword argument, Function with default argument,
Function with variable length argument
# Function with positional/required arguments
def multiply(a, b):
return a * b
print("Multiplication:", multiply(4, 5)) # Requires two arguments
# Function with keyword arguments
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
introduce(age=25, name="Alice") # Using keyword arguments
# Function with default arguments
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Uses default value
greet("Bob") # Overrides default value
# Function with variable-length arguments
def add_numbers(*numbers):
return sum(numbers)
print("Sum:", add_numbers(1, 2, 3, 4, 5)) # Accepts any number of arguments
OUTPUT
My name is Alice and I am 25 years old.
Hello, Guest!
Hello, Bob!
Sum: 15
Process finished with exit code 0
Practical 15 Write Python program to demonstrate use of following
advanced functions:
1. lambda 2. map 3. reduce
from functools import reduce
# 1. Using lambda (anonymous function)
square = lambda x: x ** 2
print("Square of 5:", square(5))
# 2. Using map() to apply a function to each item in a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print("Squared numbers:", squared_numbers)
# 3. Using reduce() to perform cumulative operations
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print("Sum of numbers:", sum_of_numbers
OUTPUT
Square of 5: 25
Squared numbers: [1, 4, 9, 16, 25]
Sum of numbers: 15
Process finished with exit code 0
Practical No. 16: Write a python program to create and use a
user defined module for a given problem
# User-defined module (math_operations.py equivalent)
# Define mathematical functions
def add(a, b):
"""Function to add two numbers."""
return a + b
def subtract(a, b):
"""Function to subtract one number from another."""
return a - b
def multiply(a, b):
"""Function to multiply two numbers."""
return a * b
def divide(a, b):
"""Function to divide two numbers."""
if b != 0:
return a / b
else:
return "Cannot divide by zero"
def square(n):
"""Function to find the square of a number."""
return n ** 2
# ------------------------------
# Main program using the module
# ------------------------------
# Using the module functions
num1, num2 = 10, 5
print("Addition:", add(num1, num2))
print("Subtraction:", subtract(num1, num2))
print("Multiplication:", multiply(num1, num2))
print("Division:", divide(num1, num2))
# Using the additional square function
print("Square of", num1, ":", square(num1))
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Square of 10 : 100
Process finished with exit code 0
Practical No. 17: Write a python program to demonstrate the use of
following
module: 1. Math module 2. Random module 3. OS module
import math
import random
import os
# 1. Using Math module
print("Math Module Demonstration:")
print("Square root of 16:", math.sqrt(16))
print("Value of Pi:", math.pi)
print("Cosine of 0 degrees:", math.cos(math.radians(0)))
print("Factorial of 5:", math.factorial(5))
print("\nRandom Module Demonstration:")
# 2. Using Random module
print("Random integer between 1 and 10:", random.randint(1, 10))
print("Random floating number between 0 and 1:", random.random())
sample_list = ["apple", "banana", "cherry"]
print("Random choice from list:", random.choice(sample_list))
random.shuffle(sample_list)
print("Shuffled list:", sample_list)
print("\nOS Module Demonstration:")
# 3. Using OS module
print("Current working directory:", os.getcwd())
print("List of files in current directory:", os.listdir())
print("User's home directory:", os.path.expanduser("~"))
OUTPUT
Math Module Demonstration:
Square root of 16: 4.0
Value of Pi: 3.141592653589793
Cosine of 0 degrees: 1.0
Factorial of 5: 120
Random Module Demonstration:
Random integer between 1 and 10: 1
Random floating number between 0 and 1: 0.4777014674571397
Random choice from list: apple
Shuffled list: ['cherry', 'banana', 'apple']
OS Module Demonstration:
Current working directory: C:\Users\USER\PycharmProjects\PythonProject6
List of files in current directory: ['.idea', '.venv', 'cha.py']
User's home directory: C:\Users\USER
Process finished with exit code 0
Practical No. 18: Write python program to create and use a user
defined package
for a given problem
# ------------------------------
# Creating a User-Defined Package
# ------------------------------
# Math Operations Module
def add(a, b):
"""Function to add two numbers."""
return a + b
def subtract(a, b):
"""Function to subtract two numbers."""
return a - b
def multiply(a, b):
"""Function to multiply two numbers."""
return a * b
def divide(a, b):
"""Function to divide two numbers."""
if b != 0:
return a / b
else:
return "Cannot divide by zero"
# String Operations Module
def to_upper(text):
"""Function to convert text to uppercase."""
return text.upper()
def to_lower(text):
"""Function to convert text to lowercase."""
return text.lower()
# ------------------------------
# Using the Package Functions
# ------------------------------
# Using Math Functions
num1, num2 = 10, 5
print("Addition:", add(num1, num2))
print("Subtraction:", subtract(num1, num2))
print("Multiplication:", multiply(num1, num2))
print("Division:", divide(num1, num2))
# Using String Functions
text = "Hello World"
print("Uppercase:", to_upper(text))
print("Lowercase:", to_lower(text))
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Uppercase: HELLO WORLD
Lowercase: hello world
Practical No. 19: Write a python program to use of numpy package
to perform operation on 2D matrix. Write a python program to use
of matplotlib package to represent data in graphical form
import numpy as np
import matplotlib.pyplot as plt
# ------------------------------
# NumPy - 2D Matrix Operations
# ------------------------------
# Creating two 2D matrices
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
# Matrix Addition
matrix_sum = np.add(matrix1, matrix2)
print("\nMatrix Addition:")
print(matrix_sum)
# Matrix Multiplication
matrix_product = np.dot(matrix1, matrix2)
print("\nMatrix Multiplication:")
print(matrix_product)
# Transpose of a Matrix
matrix_transpose = np.transpose(matrix1)
print("\nTranspose of Matrix 1:")
print(matrix_transpose)
# ------------------------------
# Matplotlib - Graphical Representation
# ------------------------------
# Sample data for plotting
x = np.arange(1, 6)
y = np.array([2, 4, 6, 8, 10])
plt.plot(x, y, marker='o', linestyle='-', color='blue', label="Linear Growth")
# Customizing the plot
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Line Plot using Matplotlib")
plt.legend()
plt.grid()
# Display the plot
plt.show()
OUTPUT
Matrix 1:
[[1 2 3]
[4 5 6]
[7 8 9]]
Matrix 2:
[[9 8 7]
[6 5 4]
[3 2 1]]
Matrix Addition:
[[10 10 10]
[10 10 10]
[10 10 10]]
Matrix Multiplication:
[[ 30 24 18]
[ 84 69 54]
[138 114 90]]
Transpose of Matrix 1:
[[1 4 7]
[2 5 8]
[3 6 9]]
Practical No. 20: Develop a python program to perform following
operations:
1. Creating a Class with method 2. Creating Objects of class
3. Accessing method using object
# Creating a class with a method
class Student:
def __init__(self, name, age):
"""Constructor to initialize Student attributes"""
self.name = name
self.age = age
def display_info(self):
"""Method to display student's information"""
print(f"Name: {self.name}, Age: {self.age}")
# Creating objects of the class
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)
# Accessing methods using objects
student1.display_info()
student2.display_info()
OUTPUT
Name: Alice, Age: 20
Name: Bob, Age: 22
Process finished with exit code 0
Practical No. 21: Write a python program to demonstrate the use of
constructors:
1Default 2. Parameterized 3. Constructor Overloading
class Student:
# Default Constructor
def __init__(self):
self.name = "Unknown"
self.age = 0
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Using Default Constructor
student1 = Student()
student1.display_info()
class Person:
# Parameterized Constructor
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Using Parameterized Constructor
person1 = Person("Alice", 25)
person1.display_info()
class Example:
# Constructor Overloading using default values
def __init__(self, a=None, b=None):
if a is not None and b is not None:
self.value = a + b
elif a is not None:
self.value = a
else:
self.value = 0
def display_value(self):
print(f"Value: {self.value}")
# Using Constructor Overloading
example1 = Example()
example2 = Example(5)
example3 = Example(5, 10)
example1.display_value()
example2.display_value()
example3.display_value()
OUTPUT
Name: Unknown, Age: 0
Name: Alice, Age: 25
Value: 0
Value: 5
Value: 15
Process finished with exit code 0
Practical No. 22: Implement a python program to demonstrate
Me class Example:
# Method Overloading using default arguments
def add(self, a, b, c=0):
return a + b + c
class Parent:
def show(self):
return "Parent class method"
class Child(Parent):
# Method Overriding
def show(self):
return "Child class method"
# Method Overloading
obj1 = Example()
print(obj1.add(10, 20)) # Calls add with 2 arguments
print(obj1.add(10, 20, 30)) # Calls add with 3 arguments
# Method Overriding
obj2 = Child()
print(obj2.show()) # Calls overridden method in Child classthod Overloading 2. Method
Overriding
OUTPUT
30
60
Child class method
Process finished with exit code 0
Practical No. 23: Write python program to demonstrate data hiding
class Example:
def __init__(self):
self.public_var = "I am public"
self.__private_var = "I am private" # Private variable
def show(self):
return f"Public: {self.public_var}, Private: {self.__private_var}"
def update_private(self, value):
self.__private_var = value
# Creating object
obj = Example()
print(obj.show())
# Attempting to access private variable directly (will cause error)
# print(obj.__private_var) # Uncommenting this line will raise AttributeError
# Accessing private variable indirectly
obj.update_private("Updated private data")
print(obj.show())
OUTPUT
Public: I am public, Private: I am private
Public: I am public, Private: Updated private data
Process finished with exit code 0
Practical No. 24: Write a python program to implement
Single inheritance 2. Multiple Inheritance 3. Multilevel inheritance
# Single Inheritance: Child class inherits from Parent class
class Parent:
def func1(self):
return "Function in Parent class"
class Child(Parent):
def func2(self):
return "Function in Child class"
# Multiple Inheritance: Child class inherits from two parent classes
class Parent1:
def funcA(self):
return "Function in Parent1 class"
class Parent2:
def funcB(self):
return "Function in Parent2 class"
class ChildMultiple(Parent1, Parent2):
def funcC(self):
return "Function in ChildMultiple class"
# Multilevel Inheritance: Child inherits from Parent, which inherits from
Grandparent
class Grandparent:
def funcX(self):
return "Function in Grandparent class"
class ParentMulti(Grandparent):
def funcY(self):
return "Function in ParentMulti class"
class ChildMulti(ParentMulti):
def funcZ(self):
return "Function in ChildMulti class"
# Demonstration of Inheritance Types
print("Single Inheritance:")
obj1 = Child()
print(obj1.func1()) # Inherited from Parent
print(obj1.func2()) # Child's own method
print("\nMultiple Inheritance:")
obj2 = ChildMultiple()
print(obj2.funcA()) # Inherited from Parent1
print(obj2.funcB()) # Inherited from Parent2
print(obj2.funcC()) # Child's own method
print("\nMultilevel Inheritance:")
obj3 = ChildMulti()
print(obj3.funcX()) # Inherited from Grandparent
print(obj3.funcY()) # Inherited from ParentMulti
print(obj3.funcZ()) # Child's own method
OUTPUT
Multilevel Inheritance:
Function in Grandparent class
Function in ParentMulti class
Function in ChildMulti class
Process finished with exit code 0
Practical No. 25: Implement Python program to perform following
operations using panda package: 1. Create Series from Array 2.
Create Series from List 3. Access element of series 4. Create
DataFrame using List or dictionary
import pandas as pd
import numpy as np # Importing NumPy for array creation
# 1. Create Series from an Array
array_data = np.array([10, 20, 30, 40])
series_from_array = pd.Series(array_data)
print("Series from Array:\n", series_from_array)
# 2. Create Series from a List
list_data = [100, 200, 300, 400]
series_from_list = pd.Series(list_data)
print("\nSeries from List:\n", series_from_list)
# 3. Access elements of a Series
print("\nAccessing element at index 2 from Series (Array-based):", series_from_array[2])
print("Accessing element at index 1 from Series (List-based):", series_from_list[1])
# 4. Create DataFrame using a List
list_dataframe = pd.DataFrame([[1, 'Alice', 25], [2, 'Bob', 30], [3, 'Charlie', 35]],
columns=['ID', 'Name', 'Age'])
print("\nDataFrame from List:\n", list_dataframe)
# 5. Create DataFrame using a Dictionary
dict_dataframe = pd.DataFrame({'ID': [101, 102, 103],
'Name': ['John', 'Jane', 'Jake'],
'Salary': [50000, 60000, 70000]})
print("\nDataFrame from Dictionary:\n", dict_dataframe)
OUTPUT
Series from Array:
0 10
1 20
2 30
3 40
dtype: int32
Series from List:
0 100
1 200
2 300
3 400
dtype: int64
Accessing element at index 2 from Series (Array-based): 30
Accessing element at index 1 from Series (List-based): 200
DataFrame from List:
ID Name Age
0 1 Alice 25
1 2 Bob 30
2 3 Charlie 35
DataFrame from Dictionary:
ID Name Salary
0 101 John 50000
1 102 Jane 60000
2 103 Jake 70000
Practical No. 26: Implement python program to load a CSV file into
a Pandas
DataFrame and perform operations.
import pandas as pd
# Load CSV file into a DataFrame
df = pd.read_csv('data.csv') # Replace 'data.csv' with your file path
# Display first 5 rows
print("\nFirst 5 rows:\n", df.head())
# Display column names
print("\nColumn names:", df.columns)
# Basic statistics of numerical columns
print("\nStatistical Summary:\n", df.describe())
# Filter data (example: selecting rows where 'Age' > 25)
filtered_data = df[df['Age'] > 25] # Replace 'Age' with actual column name
print("\nFiltered Data:\n", filtered_data)
# Sorting data by a column
sorted_data = df.sort_values(by='Salary', ascending=False) # Replace 'Salary' with actual
column name
print("\nSorted Data:\n", sorted_data)
# Handling missing values (filling with mean value)
df.fillna(df.mean(numeric_only=True), inplace=True)
print("\nData after handling missing values:\n", df.head())
OUTPUT
First 5 rows:
ID Name Age Salary
0 1 Alice 30.0 50000
1 2 Bob 22.0 40000
2 3 Charlie 28.0 60000
3 4 David 35.0 55000
4 5 Eve NaN 62000 # NaN indicates missing value
Column names: Index(['ID', 'Name', 'Age', 'Salary'], dtype='object')
Statistical Summary:
ID Age Salary
count 5.00000 4.000000 5.000000
mean 3.00000 28.75 53400.000000
std 1.58114 5.685527 8726.080
min 1.00000 22.000000 40000.000000
max 5.00000 35.000000 62000.000000
Filtered Data (Age > 25):
ID Name Age Salary
0 1 Alice 30.0 50000
2 3 Charlie 28.0 60000
3 4 David 35.0 55000
Sorted Data (Descending by Salary):
ID Name Age Salary
4 5 Eve NaN 62000
2 3 Charlie 28.0 60000
3 4 David 35.0 55000
0 1 Alice 30.0 50000
1 2 Bob 22.0 40000
Data after handling missing values:
ID Name Age Salary
0 1 Alice 30.0 50000
1 2 Bob 22.0 40000
2 3 Charlie 28.0 60000
3 4 David 35.0 55000
4 5 Eve 28.75 62000 # Missing Age replaced by mean (28.75)
Practical No. 27: Write python GUI program to import Tkinter
package and
create a window and set its title
import tkinter as tk
# Create main window
window = tk.Tk()
# Set window title
window.title("My First Tkinter Window")
# Set window size
window.geometry("400x300") # Width x Height
# Run the Tkinter event loop
window.mainloop()
OUTPUT
+--------------------------------------+
| My First Tkinter Window | <-- Title
|--------------------------------------|
| |
| (Empty Tkinter Window) |
| |
| |
Practical No. 28: Write python GUI program that adds labels and
buttons to the
Tkinter window
import tkinter as tk
# Create main window
window = tk.Tk()
# Set window properties
window.title("Tkinter GUI Example")
window.geometry("400x300") # Width x Height
# Create a label
label = tk.Label(window, text="Welcome to My Tkinter Window!", font=("Arial", 14))
label.pack(pady=20) # Adds space around label
# Function for button click action
def on_button_click():
label.config(text="Button Clicked!") # Update label text
# Create a button
button = tk.Button(window, text="Click Me", command=on_button_click)
button.pack(pady=10) # Adds space around button
# Run the Tkinter event loop
window.mainloop()
OUTPUT
+--------------------------------------+
| Tkinter GUI Example | <-- Title
|--------------------------------------|
| |
| Welcome to My Tkinter Window! | <-- Label
| |
| [ Click Me ] | <-- Button
| |
+--------------------------------------+
Practical No. 29: Write program to create a connection between
database and Python import sqlite3
# Create or connect to a database
connection = sqlite3.connect("my_database.db") # Creates a database file
# Create a cursor object to interact with the database
cursor = connection.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)''')
# Insert data into the table
cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 22)")
cursor.execute("INSERT INTO students (name, age) VALUES ('Bob', 25)")
# Commit changes
connection.commit()
# Fetch and display data
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nStudents Table:")
for row in rows:
print(row)
# Close the connection
connection.close()
OUTPUT
Students Table:
(1, 'Alice', 22)
(2, 'Bob', 25)
Practical No. 30: Implement python program to select records from
the database
table and display the result
import sqlite3
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table (if it doesn't exist)
cursor.execute('''CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)''')
# Insert sample data
cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 22)")
cursor.execute("INSERT INTO students (name, age) VALUES ('Bob', 24)")
cursor.execute("INSERT INTO students (name, age) VALUES ('Charlie', 23)")
conn.commit()
# Select records from the table
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
# Display the results
print("Student Records:")
for row in rows:
print(row)
# Close the connection
conn.close()
OUTPUT
Student Records:
(1, 'Alice', 22)
(2, 'Bob', 24)
(3, 'Charlie', 23)
By Chaitanya