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

Python Programming Practical No 16to 30

The document contains various Python programming exercises that demonstrate the creation and use of user-defined modules, packages, and classes. It includes examples of mathematical operations, string manipulations, and graphical representations using libraries like NumPy and Matplotlib. Additionally, it covers concepts such as constructors, method overloading, and overriding in object-oriented programming.

Uploaded by

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

Python Programming Practical No 16to 30

The document contains various Python programming exercises that demonstrate the creation and use of user-defined modules, packages, and classes. It includes examples of mathematical operations, string manipulations, and graphical representations using libraries like NumPy and Matplotlib. Additionally, it covers concepts such as constructors, method overloading, and overriding in object-oriented programming.

Uploaded by

tejaswilokhande8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Practical No.

16
Write a python program to create and use a user defined module for a given
problem
import shapes # Import the user-defined module
# Input for rectangle

length = float(input("Enter the length of the rectangle: "))


width = float(input("Enter the width of the rectangle: "))
# Calculate and display rectangle area
rect_area = shapes.rectangle_area(length, width)
print(f"Area of the rectangle: {rect_area}")

# Input for circle


radius = float(input("Enter the radius of the circle: "))
# Calculate and display circle area
circ_area = shapes.circle_area(radius)
print(f"Area of the circle: {circ_area}")

Output:
Practical related questions:
4.Write a Python program to create a user defined module that will ask your
college name and will display the name of the college.
Step 1:
def ask_college_name():

name = input("Enter your college name: ")


return name
def display_college_name(name):
print("Your college name is:", name)

Step 2:
import college
college_name = college.ask_college_name()
college.display_college_name(college_name)
Step 1: Output

Step 2: Output
5.Write a Python program to define a module to find Fibonacci Numbers and
import the module to another program.
Step 1:
def fibonacci(n):
a, b = 0, 1

fib_series = []
for _ in range(n):
fib_series.append(a)
a, b = b, a + b
return fib_series

Step 2:
import fibonacci
n = int(input("Enter the number of Fibonacci terms: "))
result = fibonacci.fibonacci(n)
print("Fibonacci Series:", result)
Step 1: Output

Step 2: Output
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. Math module demonstration
num = 16
print("Square root of", num, "is:", math.sqrt(num))
print("Factorial of 5 is:", math.factorial(5))

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


# 2. Random module demonstration
print("Random integer between 1 and 10:", random.randint(1, 10))
print("Random floating number between 0 and 1:", random.random())
print("Random choice from a list:", random.choice(["Apple", "Banana", "Cherry"]))

# 3. OS module demonstration
print("Current working directory:", os.getcwd())
print("List of files in current directory:", os.listdir())
# Creating a new directory (Uncomment the below line if you want to create a folder)
# os.mkdir("TestFolder")

# Getting the OS name


print("Operating System Name:", os.name)
Output:
Practical related questions
1.Write a Python program to display calendar of given month using Calendar
module.
import calendar
year = int(input("Enter year: "))

month = int(input("Enter month (1-12): "))


print("\nCalendar for", calendar.month_name[month], year)
print(calendar.month(year, month))

Output:
2.Write a python program to calculate area of circle using inbuilt Math module.
import math
radius = float(input("Enter the radius of the circle: "))

area = math.pi * radius * radius


print("Area of the circle is:", area)

Output:
3.What is the output of the following program?
import random
print random.randint(0, 5)
print random.random()
print random.random() * 100
List = [1, 4, True, 800, "Python", 27, "hello"]
print random.choice(List)

Output:
4.What is the output of the following program?
import datetime
from datetime import date
import time print time.time()
print date.fromtimestamp(454554)

Output:
Practical No. 18
Write python program to create and use a user defined package for a given
problem
# mathoperations/arithmetic.py
def add(a, b):

return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b

def divide(a, b):


if b == 0:
return "Cannot divide by zero"
return a / b
# main.py

from mathoperations.arithmetic import add, subtract, multiply, divide


a = 10
b=5
print("Addition:", add(a, b))
print("Subtraction:", subtract(a, b))

print("Multiplication:", multiply(a, b))


print("Division:", divide(a, b))
Output:

Output:
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
# Create a 2D matrix using numpy
matrix = np.array([[1, 2, 3],

[4, 5, 6],
[7, 8, 9]])
print("Original Matrix:")
print(matrix)
# Perform various operations on the 2D matrix

# 1. Transpose of the matrix


transpose_matrix = np.transpose(matrix)
print("\nTranspose of the Matrix:")
print(transpose_matrix)
# 2. Matrix addition

matrix_to_add = np.array([[9, 8, 7],


[6, 5, 4],
[3, 2, 1]])
sum_matrix = matrix + matrix_to_add
print("\nMatrix Addition:")

print(sum_matrix)
# 3. Matrix multiplication
matrix_to_multiply = np.array([[1, 2],
[3, 4],
[5, 6]])

product_matrix = np.dot(matrix, matrix_to_multiply)


print("\nMatrix Multiplication:")
print(product_matrix)
# 4. Element-wise multiplication
element_wise_product = matrix * matrix_to_add

print("\nElement-wise Multiplication:")
print(element_wise_product)
# 5. Determinant of the matrix
determinant = np.linalg.det(matrix)
print("\nDeterminant of the Matrix:")

print(determinant)
Output:
import matplotlib.pyplot as plt
# Example data
years = [2015, 2016, 2017, 2018, 2019, 2020]

values = [10, 15, 7, 10, 25, 30]


# Line plot
plt.figure(figsize=(8, 5))
plt.plot(years, values, marker='o', linestyle='-', color='b', label='Values')
plt.xlabel('Year')

plt.ylabel('Value')
plt.title('Line Plot Example')
plt.legend()
plt.grid(True)
plt.show()

# Bar chart
plt.figure(figsize=(8, 5))
plt.bar(years, values, color='c', label='Values')
plt.xlabel('Year')
plt.ylabel('Value')

plt.title('Bar Chart Example')


plt.legend()
plt.grid(True)
plt.show()
Output:
Practical Related Questions
1. Write a Python program to create two matrices and perform addition,
subtraction,
multiplication and division operation on matrix using NumPy
import numpy as np

# Define two 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)
# Perform matrix addition
matrix_sum = matrix1 + matrix2
print("\nSum of Matrix 1 and Matrix 2:")
print(matrix_sum)

# Perform matrix subtraction


matrix_difference = matrix1 - matrix2
print("\nDifference of Matrix 1 and Matrix 2:")
print(matrix_difference)
# Perform element-wise matrix multiplication

matrix_product = matrix1 * matrix2


print("\nElement-wise Multiplication of Matrix 1 and Matrix 2:")
print(matrix_product)
# Perform element-wise matrix division
matrix_division = matrix1 / matrix2
print("\nElement-wise Division of Matrix 1 by Matrix 2:")
print(matrix_division)

Output:
2] Write a python program to concatenate two strings using NumPy.
import numpy as np
# Define two arrays of strings

array1 = np.array(['Hello', 'Good'])


array2 = np.array(['World', 'Morning'])
# Concatenate the arrays of strings using np.char.add
concatenated_array = np.char.add(array1, array2)
# Print the concatenated array

print("Concatenated Array:")
print(concatenated_array)

Output:
3] Write a NumPy program to generate six random integers between 10 and 30.
import numpy as np
# Generate six random integers between 10 and 30

random_integers = np.random.randint(10, 31, size=6)


# Print the random integers
print("Six random integers between 10 and 30:")
print(random_integers)

Output:
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
class MyClass:
def display_message(self):

print("Hello! This is a method inside a class.")


obj = MyClass()
obj.display_message()

Output:
Practical related questions
1.Write a Python class to implement pow(x, n)
class Power:
def my_pow(self, x, n):
result = 1
if n < 0:
x=1/x
n = -n

while n:
if n % 2:
result *= x
x *= x
n //= 2

return result

# Example usage:
power = Power()
print(power.my_pow(2, 10))

Output:
2. Write a Python class to reverse a string word by word.
class Power:
def my_pow(self, x, n):
result = 1
if n < 0:
x=1/x
n = -n
while n:
if n % 2:
result *= x
x *= x
n //= 2
return result
class ReverseString:
def reverse_words(self, s):
return ' '.join(s.split()[::-1])
# Example usage:
power = Power()
print(power.my_pow(2, 10)) # Output: 1024
reverse_string = ReverseString()
print(reverse_string.reverse_words("Hello World"))

Output:
3. Write a Python class to convert an integer to a roman numeral.
class Power:
def my_pow(self, x, n):
result = 1
if n < 0:
x=1/x
n = -n
while n:
if n % 2:
result *= x
x *= x
n //= 2
return result
class ReverseString:
def reverse_words(self, s):
return ' '.join(s.split()[::-1])
class IntegerToRoman:
def int_to_roman(self, num):
val = [
(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
]
roman = ""
for v, symbol in val:
while num >= v:
roman += symbol
num -= v
return roman
# Example usage:
power = Power()
print(power.my_pow(2, 10)) # Output: 1024
reverse_string = ReverseString()
print(reverse_string.reverse_words("Hello World")) # Output: "World Hello"
integer_to_roman = IntegerToRoman()
print(integer_to_roman.int_to_roman(1994))
Output:
4. Write a Python class that has two methods: get_String and print_String ,
get_String accept a string from the user and print_String prints the string in
upper case.
class StringManipulator:
def __init__(self):
self.string = "
def get_String(self, user_input):

self.string = user_input
def print_String(self):
print(self.string.upper())
# Example usage:
string_manipulator = StringManipulator()

string_manipulator.get_String("hello world")
string_manipulator.print_String()

Output:
5. Write a Python class named Rectangle constructed from length and width
and a method that will compute the area of a rectangle
class Main:
def __init__(self, length, width):
self.length = length

self.width = width
def area(self):
return self.length * self.width
# Create a rectangle object
rectangle = Main(5, 3)

# Print the area


print("Area of the rectangle:", rectangle.area())

Output:
Practical No. 21
Write a python program to demonstrate the use of constructors: 1. Default 2.
Parameterized 3. Constructor Overloading
class Main:
# Default Constructor

def __init__(self, length=0, width=0):


self.length = length
self.width = width
# Method to calculate area
def area(self):

return self.length * self.width


# Parameterized Constructor
def set_dimensions(self, length, width):
self.length = length
self.width = width

# Constructor Overloading using default arguments


def display(self, length=None, width=None):
if length is not None and width is not None:
print("Area with provided dimensions:", length * width)
else:

print("Area with default dimensions:", self.length * self.width)


# Demonstrating Default Constructor
rect1 = Main() # Uses default values of 0 for length and width
print("Area using default constructor:", rect1.area())
# Demonstrating Parameterized Constructor

rect2 = Main(5, 3) # Uses values passed during object creation


print("Area using parameterized constructor:", rect2.area())
# Demonstrating Constructor Overloading (with default arguments)
rect3 = Main(6, 4) # Uses parameterized constructor
rect3.display() # Uses default values of rect3
rect3.display(8, 2) # Uses provided dimensions in the method

Output:
Practical related questions
3. Write a python program to implement parameterized constructor.
class Main:

def __init__(self, length, width):


self.length = length
self.width = width
def area(self):
return self.length * self.width

# Creating an object with parameters passed to the constructor


rect = Main(5, 3)
# Display the area of the rectangle
print("Area of the rectangle:", rect.area())

Output:
4. Write a python program to implement constructor overloading.
class Main:
def __init__(self, *args):

if len(args) == 1:
self.length = self.width = args[0] # For a square
elif len(args) == 2:
self.length, self.width = args # For a rectangle
else:

self.length = self.width = 0 # Default case


def area(self):
return self.length * self.width
# Creating objects using different constructor styles
square = Main(4) # This simulates a square with side length 4

rectangle = Main(5, 3) # This simulates a rectangle with length 5 and width 3


default = Main() # Default constructor
# Displaying areas
print("Area of the square:", square.area()) # 16
print("Area of the rectangle:", rectangle.area()) # 15

print("Area with default dimensions:", default.area()) # 0


Output:
Practical No. 22
Implement a python program to demonstrate 1. Method Overloading 2.
Method Overriding
# Parent Class demonstrating Method Overriding
class Shape:

def area(self):
print("Area method of Shape class")
# Subclass demonstrating Method Overriding
class Rectangle(Shape):
def area(self):

print("Area method of Rectangle class")


# Parent Class demonstrating Method Overloading Simulation
class Calculator:
# Simulating Method Overloading using default arguments
def add(self, *args):

if len(args) == 1:
print(f"Addition of one number: {args[0]}")
elif len(args) == 2:
print(f"Addition of two numbers: {args[0] + args[1]}")
else:

print("Invalid number of arguments")


# Demonstrating Method Overriding
shape = Shape()
shape.area() # Calls parent class method
rectangle = Rectangle()

rectangle.area() # Calls overridden method in subclass


# Demonstrating Method Overloading Simulation
calc = Calculator()
calc.add(5) # Calls method with one argument
calc.add(3, 7) # Calls method with two arguments
calc.add() # Calls method with invalid arguments

Output:
Practical related questions
1.Write a Python program to create a class to print the area of a square and a
rectangle. The class has two methods with the same name but different
number of parameters. The method for printing area of rectangle has two
parameters which are length and breadth respectively while the other method
for printing area of square has one parameter which is side of square.
class Main:
# Method for calculating area of a rectangle
def area(self, length, breadth=None):
if breadth is None:

# This part calculates area of square when only one argument is passed
area = length * length
print(f"Area of the square: {area}")
else:
# This part calculates area of rectangle when two arguments are passed

area = length * breadth


print(f"Area of the rectangle: {area}")
# Create an object of the class
shape = Main()
# Call the area method to calculate area of a square

shape.area(4) # Square with side 4


# Call the area method to calculate area of a rectangle
shape.area(5, 3) # Rectangle with length 5 and breadth 3
Output:
3. Write a Python program to create a class 'Degree' having a method
'getDegree' that prints "I got a degree". It has two subclasses namely
'Undergraduate' and Postgraduate' each having a method with the same name
that prints "I am an Undergraduate" and "I am a Postgraduate" respectively.
Call the method by creating an object of each of the three classes.
class Degree:
def getDegree(self):
print("I got a degree")
class Undergraduate(Degree):
def getDegree(self):

print("I am an Undergraduate")
class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")
# Creating objects of each class

degree = Degree()
undergraduate = Undergraduate()
postgraduate = Postgraduate()
# Calling the getDegree method
degree.getDegree() # Calls the method from the Degree class

undergraduate.getDegree() # Calls the overridden method from the Undergraduate class


postgraduate.getDegree() # Calls the overridden method from the Postgraduate class
Output:
Practical No. 23
Write python program to demonstrate data hiding
class BankAccount:

def __init__(self, owner, balance):


self.owner = owner
self.__balance = balance # Private variable
def deposit(self, amount):
if amount > 0:

self.__balance += amount
print(f"Deposited {amount}. New balance is {self.__balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):

if 0 < amount <= self.__balance:


self.__balance -= amount
print(f"Withdrew {amount}. New balance is {self.__balance}")
else:
print("Invalid withdrawal amount or insufficient balance.")

def __get_balance(self): # Private method


return self.__balance
def display_balance(self):
print(f"Balance for {self.owner}: {self.__balance}")
# Creating an object of BankAccount class

account = BankAccount("John", 1000)


# Accessing public methods
account.deposit(500)
account.withdraw(300)
# Direct access to private variable (will raise an AttributeError)
# print(account.__balance) # Uncommenting this line will raise an error
# Direct access to private method (will raise an AttributeError)
# print(account.__get_balance()) # Uncommenting this line will raise an error
# Correct way to display balance using the public method

account.display_balance()

Output:
Practical related questions
3. Write a Python program to implement data hiding
class Account:

def __init__(self, owner, balance):


self.owner = owner
self.__balance = balance # Private variable
# Public method to access private balance
def deposit(self, amount):

if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}. New balance: {self.__balance}")
else:
print("Deposit amount must be positive.")

# Public method to access private balance


def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew: {amount}. New balance: {self.__balance}")

else:
print("Invalid withdrawal amount or insufficient balance.")
# Public method to display the balance
def display_balance(self):
print(f"Balance for {self.owner}: {self.__balance}")

# Private method
def __get_balance(self):
return self.__balance
# Creating an object of Account class
account = Account("John", 1000)
# Accessing public methods
account.deposit(500)
account.withdraw(300)
# Trying to directly access the private variable (Will raise an error)

# print(account.__balance) # Uncommenting this line will raise an error


# Trying to directly access the private method (Will raise an error)
# print(account.__get_balance()) # Uncommenting this line will raise an error
# Displaying the balance using a public method
account.display_balance()

Output:
Practical No. 24
Write a python program to implement 1. Single inheritance 2. Multiple
Inheritance 3. Multilevel inheritance
# 1. Single Inheritance
class Animal:

def speak(self):
print("Animal speaks")
class Dog(Animal): # Dog is inheriting from Animal
def bark(self):
print("Dog barks")

# Creating an object of Dog class


dog = Dog()
dog.speak() # Method from the parent class Animal
dog.bark() # Method from the Dog class
# 2. Multiple Inheritance

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):

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


class Address:
def __init__(self, city, country):
self.city = city
self.country = country

def location(self):
print(f"City: {self.city}, Country: {self.country}")
class Employee(Person, Address): # Inheriting from both Person and Address
def __init__(self, name, age, city, country, job_title):
Person.__init__(self, name, age)
Address.__init__(self, city, country)
self.job_title = job_title

def employee_details(self):
print(f"Job Title: {self.job_title}")
self.details() # Calling method from Person class
self.location() # Calling method from Address class
# Creating an object of Employee class

employee = Employee("Alice", 30, "New York", "USA", "Software Engineer")


employee.employee_details() # Calling the method from the Employee class
# 3. Multilevel Inheritance
class Vehicle:
def start(self):

print("Vehicle started")
class Car(Vehicle): # Car is inheriting from Vehicle
def drive(self):
print("Car is driving")
class ElectricCar(Car): # ElectricCar is inheriting from Car, which inherits from Vehicle

def charge(self):
print("Electric car is charging")
# Creating an object of ElectricCar class
electric_car = ElectricCar()
electric_car.start() # Method from Vehicle class

electric_car.drive() # Method from Car class


electric_car.charge() # Method from ElectricCar class
Output:
Practical related questions
2. Write Python program to read and print students information using single
inheritance.
class Student:
def __init__(self, name, roll_no):

self.name = name
self.roll_no = roll_no
def display(self):
print("Name:", self.name)
print("Roll No:", self.roll_no)

class StudentDetails(Student):
def __init__(self, name, roll_no, marks):
super().__init__(name, roll_no)
self.marks = marks
def display(self):

super().display()
print("Marks:", self.marks)
name = input("Enter student name: mohit")
roll_no = input("Enter roll number: 10")
marks = float(input("Enter marks: 69"))

s = StudentDetails(name, roll_no, marks)


s.display()
Output:
3. Write a Python program to implement multiple inheritance.
class Person:
def __init__(self, name, age):

self.name = name
self.age = age
def display_person(self):
print("Name:", self.name)
print("Age:", self.age)

class Student:
def __init__(self, roll_no, marks):
self.roll_no = roll_no
self.marks = marks
def display_student(self):

print("Roll No:", self.roll_no)


print("Marks:", self.marks)
class StudentDetails(Person, Student):
def __init__(self, name, age, roll_no, marks):
Person.__init__(self, name, age)

Student.__init__(self, roll_no, marks)


def display(self):
self.display_person()
self.display_student()
name = input("Enter student name: ")

age = int(input("Enter age: "))


roll_no = input("Enter roll number: ")
marks = float(input("Enter marks: "))
s = StudentDetails(name, age, roll_no, marks)
s.display()
Output:
4. Write a Python program to implement multilevel inheritance.
class Person:
def __init__(self, name, age):

self.name = name
self.age = age
def display_person(self):
print("Name:", self.name)
print("Age:", self.age)

class Student(Person):
def __init__(self, name, age, roll_no):
super().__init__(name, age)
self.roll_no = roll_no
def display_student(self):

print("Roll No:", self.roll_no)


class Exam(Student):
def __init__(self, name, age, roll_no, marks):
super().__init__(name, age, roll_no)
self.marks = marks

def display_exam(self):
self.display_person()
self.display_student()
print("Marks:", self.marks)
try:

name = input("Enter student name: ")


age = int(input("Enter age: "))
roll_no = input("Enter roll number: ")
marks = float(input("Enter marks: "))
s = Exam(name, age, roll_no, marks)
s.display_exam()
except Exception as e:
print("Error:", e)

Output:
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
# 1. Create Series from Array

array_data = np.array([10, 20, 30, 40, 50])


series_from_array = pd.Series(array_data)
print("Series from Array:")
print(series_from_array)
# 2. Create Series from List

list_data = [100, 200, 300, 400, 500]


series_from_list = pd.Series(list_data)
print("\nSeries from List:")
print(series_from_list)
# 3. Access element of Series

element_at_index_2 = series_from_list[2]
print("\nElement at index 2 of Series from List:")
print(element_at_index_2)
# 4. Create DataFrame using List or Dictionary
# Creating DataFrame from List of Lists

data_list = [[1, 'Alice', 25], [2, 'Bob', 30], [3, 'Charlie', 35]]
df_from_list = pd.DataFrame(data_list, columns=['ID', 'Name', 'Age'])
print("\nDataFrame from List of Lists:")
print(df_from_list)
# Creating DataFrame from Dictionary

data_dict = {
'ID': [1, 2, 3],
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}

df_from_dict = pd.DataFrame(data_dict)
print("\nDataFrame from Dictionary:")
print(df_from_dict)

Output:
Practical Related Questions
1 Write a Python program to create series from array using Panda
import pandas as pd

import numpy as np
# Create an array using numpy
array_data = np.array([10, 20, 30, 40, 50])
# Create a Series from the array using pandas
series_from_array = pd.Series(array_data)

# Print the Series


print("Series from Array:")
print(series_from_array)

Output:
2 Write a Python program to create series from list using Panda
import pandas as pd
# Create a list

list_data = [100, 200, 300, 400, 500]


# Create a Series from the list using pandas
series_from_list = pd.Series(list_data)
# Print the Series
print("Series from List:")

print(series_from_list)

Output:
3] Write a Python program to access element of series using Panda
import pandas as pd
# Create a Series from a list

list_data = [100, 200, 300, 400, 500]


series_from_list = pd.Series(list_data)
# Access and print elements of the Series
print("Series from List:")
print(series_from_list)

# Access element at index 2


element_at_index_2 = series_from_list[2]
print("\nElement at index 2 of the Series:")
print(element_at_index_2)
# Access elements using slicing

elements_slice = series_from_list[1:4]
print("\nElements from index 1 to 3 (inclusive) using slicing:")
print(elements_slice)
Output:
4] Write a Python program to create DataFrame using list or dictionary using
Panda
import pandas as pd
# Creating DataFrame from List of Lists
data_list = [[1, 'Alice', 25], [2, 'Bob', 30], [3, 'Charlie', 35]]

df_from_list = pd.DataFrame(data_list, columns=['ID', 'Name', 'Age'])


print("DataFrame from List of Lists:")
print(df_from_list)
# Creating DataFrame from Dictionary
data_dict = {

'ID': [1, 2, 3],


'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df_from_dict = pd.DataFrame(data_dict)

print("\nDataFrame from Dictionary:")


print(df_from_dict)

Output:
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 DataFrame

file_path = r'C:\Users\sudha\OneDrive\Desktop\PYTHON PROGRAMMING\example.csv' #


Replace with the path to your CSV file

data = pd.read_csv(file_path)
# Display the first few rows of the DataFrame
print("First few rows of the DataFrame:")
print(data.head())
# Display the summary statistics of the DataFrame

print("\nSummary statistics of the DataFrame:")


print(data.describe())
# Select a specific column
column_name = 'Name'
print(f"\nSelected column '{column_name}':")

print(data[column_name])
# Filter rows based on a condition
condition = data['Age'] > 25
filtered_data = data[condition]
print(f"\nRows where 'Age' is greater than 25:")
print(filtered_data)
# Perform groupby operation
grouped_data = data.groupby('Age').sum()
print("\nGrouped data by 'Age' and calculated sum:")
print(grouped_data)
Output:
Practical related questions
1] Write a Python program to read and write with CSV files using pandas
import pandas as pd

# Load CSV file into DataFrame


file_path = r'C:\Users\sudha\OneDrive\Desktop\PYTHON PROGRAMMING\example.csv' #
Replace with the path to your CSV file
data = pd.read_csv(file_path)
# Display the first few rows of the DataFrame
print("First few rows of the DataFrame:")
print(data.head())

# Modify the DataFrame (example: add a new column)


data['NewColumn'] = data['Age'] * 2 # Replace 'Age' with an actual column name in your CSV
file
# Display the modified DataFrame
print("\nModified DataFrame:")
print(data.head())
# Write DataFrame to a new CSV file

write_file_path = r'C:\Users\sudha\OneDrive\Desktop\PYTHON
PROGRAMMING\output_file.csv' # Replace with the path to your output CSV file
data.to_csv(write_file_path, index=False)
print(f"\nDataFrame has been written to '{write_file_path}'")

Output:
Practical No. 27
Write python GUI program to import Tkinter package and create a window and
set its title
import tkinter as tk
# Create the main window

root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")
# Set the size of the window (optional)
root.geometry("400x300")

# Run the application


root.mainloop()

Output:
Practical related questions
3. Write GUI program to import Tkinter package and create a window and set
its title.
import tkinter as tk
# Create the main window

root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")
# Set window size (optional)
root.geometry("400x300")

# Run the Tkinter event loop


root.mainloop()

Output:
Practical No. 28
Write python GUI program that adds labels and buttons to the Tkinter window
import tkinter as tk

# Create the main window


root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")
# Set window size (optional)

root.geometry("400x300")
# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
# Add a button

button = tk.Button(root, text="Click Me")


button.pack(pady=5)
# Run the Tkinter event loop
root.mainloop()
Output:
Practical related questions
2. Write a Python program using Tkinter that creates a CheckButton.
import tkinter as tk

# Create the main window


root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")
# Set window size (optional)

root.geometry("400x300")
# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
# Add a button

button = tk.Button(root, text="Click Me")


button.pack(pady=5)
# Add a CheckButton
check_var = tk.IntVar()
check_button = tk.Checkbutton(root, text="Check Me", variable=check_var)

check_button.pack(pady=5)
# Run the Tkinter event loop
root.mainloop()
Output:
3. Write a Python program using Tkinter that creates a RadioButton.
import tkinter as tk
# Create the main window

root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")
# Set window size (optional)
root.geometry("400x300")

# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
# Add a button
button = tk.Button(root, text="Click Me")

button.pack(pady=5)
# Add a CheckButton
check_var = tk.IntVar()
check_button = tk.Checkbutton(root, text="Check Me", variable=check_var)
check_button.pack(pady=5)

# Add RadioButtons
radio_var = tk.IntVar()
radio1 = tk.Radiobutton(root, text="Option 1", variable=radio_var, value=1)
radio2 = tk.Radiobutton(root, text="Option 2", variable=radio_var, value=2)
radio1.pack(pady=5)

radio2.pack(pady=5)
# Run the Tkinter event loop
root.mainloop()
Output:
4. Write a Python program using Tkinter that creates a Menu.
import tkinter as tk
# Create the main window

root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")
# Set window size (optional)
root.geometry("400x300")

# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
# Add a button
button = tk.Button(root, text="Click Me")

button.pack(pady=5)
# Add a CheckButton
check_var = tk.IntVar()
check_button = tk.Checkbutton(root, text="Check Me", variable=check_var)
check_button.pack(pady=5)

# Add RadioButtons
radio_var = tk.IntVar()
radio1 = tk.Radiobutton(root, text="Option 1", variable=radio_var, value=1)
radio2 = tk.Radiobutton(root, text="Option 2", variable=radio_var, value=2)
radio1.pack(pady=5)

radio2.pack(pady=5)
# Create a menu
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open")
file_menu.add_command(label="Save")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

menu_bar.add_cascade(label="File", menu=file_menu)
# Run the Tkinter event loop
root.mainloop()

Output:
Practical No. 29
Write program to create a connection between database and python
import tkinter as tk

import sqlite3
# Create the main window
root = tk.Tk()
# Set the title of the window
root.title("My Tkinter Window")

# Set window size (optional)


root.geometry("400x300")
# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)

# Add a button
button = tk.Button(root, text="Click Me")
button.pack(pady=5)
# Add a CheckButton
check_var = tk.IntVar()

check_button = tk.Checkbutton(root, text="Check Me", variable=check_var)


check_button.pack(pady=5)
# Add RadioButtons
radio_var = tk.IntVar()
radio1 = tk.Radiobutton(root, text="Option 1", variable=radio_var, value=1)

radio2 = tk.Radiobutton(root, text="Option 2", variable=radio_var, value=2)


radio1.pack(pady=5)
radio2.pack(pady=5)
# Create a menu
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open")
file_menu.add_command(label="Save")

file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
# Connect to SQLite database
def connect_db():

conn = sqlite3.connect("my_database.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
conn.commit()
conn.close()

print("Database connected and table created")


# Create a database connection button
db_button = tk.Button(root, text="Connect to Database", command=connect_db)
db_button.pack(pady=5)
# Run the Tkinter event loop

root.mainloop()
Output:
Practical related questions
3. Write program to connect Python with PostgreSQL Database.
import tkinter as tk

import sqlite3

# Create the main window

root = tk.Tk()

# Set the title of the window

root.title("My Tkinter Window")

# Set window size (optional)

root.geometry("400x300")

# Add a label

label = tk.Label(root, text="Hello, Tkinter!")

label.pack(pady=10)

# Add a button

button = tk.Button(root, text="Click Me")

button.pack(pady=5)

# Add a CheckButton

check_var = tk.IntVar()

check_button = tk.Checkbutton(root, text="Check Me", variable=check_var)

check_button.pack(pady=5)

# Add RadioButtons

radio_var = tk.IntVar()

radio1 = tk.Radiobutton(root, text="Option 1", variable=radio_var, value=1)

radio2 = tk.Radiobutton(root, text="Option 2", variable=radio_var, value=2)

radio1.pack(pady=5)

radio2.pack(pady=5)

# Create a menu

menu_bar = tk.Menu(root)

root.config(menu=menu_bar)

file_menu = tk.Menu(menu_bar, tearoff=0)

file_menu.add_command(label="Open")
file_menu.add_command(label="Save")

file_menu.add_separator()

file_menu.add_command(label="Exit", command=root.quit)

menu_bar.add_cascade(label="File", menu=file_menu)

# Connect to SQLite database

def connect_sqlite_db():

conn = sqlite3.connect("my_database.db")

cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")

conn.commit()

conn.close()

print("SQLite Database connected and table created")

# Connect to PostgreSQL database

def connect_postgres_db():

try:

conn = psycopg2.connect(

dbname="your_dbname",

user="your_username",

password="your_password",

host="your_host",

port="your_port"

cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)")

conn.commit()

cursor.close()

conn.close()

print("PostgreSQL Database connected and table created")

except psycopg2.Error as e:

print("Error connecting to PostgreSQL:", e)

# Create database connection buttons


db_sqlite_button = tk.Button(root, text="Connect to SQLite", command=connect_sqlite_db)

db_sqlite_button.pack(pady=5)

db_postgres_button = tk.Button(root, text="Connect to PostgreSQL",


command=connect_postgres_db)

db_postgres_button.pack(pady=5)

# Run the Tkinter event loop

root.mainloop()

Output:
Practical No. 30
Implement python program to select records from the database table and
display the result
import sqlite3
# Connect to the SQLite database (it will create a new one if it doesn't exist)

conn = sqlite3.connect('example.db')
# Create a cursor object
cursor = conn.cursor()
# Create a sample table (only needed once, to set up your database)
cursor.execute('''

CREATE TABLE IF NOT EXISTS users (


id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)

''')
# Insert some sample data (only needed once, to populate your table)
cursor.execute("INSERT INTO users (name, age) VALUES ('John Doe', 25)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Jane Smith', 30)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Mike Johnson', 35)")

# Commit the changes


conn.commit()
# Execute a SELECT query to fetch records from the 'users' table
cursor.execute("SELECT * FROM users")
# Fetch all records

records = cursor.fetchall()
# Display the records
print("ID | Name | Age")
print("-------------------------")
for record in records:
print(f"{record[0]} | {record[1]} | {record[2]}")
# Close the connection

conn.close()

Output:

You might also like