Python Programming Practical No 16to 30
Python Programming Practical No 16to 30
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
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():
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))
# 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")
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: "))
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
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
print(sum_matrix)
# 3. Matrix multiplication
matrix_to_multiply = np.array([[1, 2],
[3, 4],
[5, 6]])
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]
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')
[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)
Output:
2] Write a python program to concatenate two strings using NumPy.
import numpy as np
# Define two arrays of strings
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
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):
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)
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
Output:
Practical related questions
3. Write a python program to implement parameterized constructor.
class Main:
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:
def area(self):
print("Area method of Shape class")
# Subclass demonstrating Method Overriding
class Rectangle(Shape):
def area(self):
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:
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
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
self.__balance += amount
print(f"Deposited {amount}. New balance is {self.__balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
account.display_balance()
Output:
Practical related questions
3. Write a Python program to implement data hiding
class Account:
if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}. New balance: {self.__balance}")
else:
print("Deposit amount must be positive.")
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)
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")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):
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
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
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"))
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):
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):
def display_exam(self):
self.display_person()
self.display_student()
print("Marks:", self.marks)
try:
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
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)
Output:
2 Write a Python program to create series from list using Panda
import pandas as pd
# Create a 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
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]]
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
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(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
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")
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")
Output:
Practical No. 28
Write python GUI program that adds labels and buttons to the Tkinter window
import tkinter as tk
root.geometry("400x300")
# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
# Add a button
root.geometry("400x300")
# Add a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
# Add a button
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")
# Add a button
button = tk.Button(root, text="Click Me")
button.pack(pady=5)
# Add a CheckButton
check_var = tk.IntVar()
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()
root.mainloop()
Output:
Practical related questions
3. Write program to connect Python with PostgreSQL Database.
import tkinter as tk
import sqlite3
root = tk.Tk()
root.geometry("400x300")
# Add a label
label.pack(pady=10)
# Add a button
button.pack(pady=5)
# Add a CheckButton
check_var = tk.IntVar()
check_button.pack(pady=5)
# Add RadioButtons
radio_var = tk.IntVar()
radio1.pack(pady=5)
radio2.pack(pady=5)
# Create a menu
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
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)
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()
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()
except psycopg2.Error as e:
db_sqlite_button.pack(pady=5)
db_postgres_button.pack(pady=5)
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('''
''')
# 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)")
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: