Python an Kit
Python an Kit
-1323472 BCA-406
A
(BCA-406)
Practical File On
Python Programing Lab
BCA-406
1
Roll no.-1323472 BCA-406
SN NO. PROGRAM LIST PAGE NO. DATE SIGNATURE
01. Installation of python and Jupyter Notebook (IDE
for Python) and test a basic python program in
both Script and Interactive mode
2
Roll no.-1323472 BCA-406
Practical-01
Installation of python and Jupyter Notebook (IDE for Python) and test a basic python
program in both Script and Interactive mode
➢ Download Python:
• Go to the official Python website: https://www.python.org/downloads/
• Choose the appropriate version for your operating system (Windows, macOS, Linux).
• Download and install Python. During installation, make sure to check the box to "Add Python
to PATH" before clicking "Install Now."
➢ Verify Python installation: Open a terminal or command prompt and run the following
command to verify that Python is installed correctly:
➢ Install Jupyter using pip: After installing Python, open a terminal or command prompt and run the
following command to install Jupyter Notebook using pip:
➢ Launch Jupyter Notebook: After installation, you can launch Jupyter Notebook by running the
following command in your terminal or command prompt:
3
Roll no.-1323472 BCA-406
➢ Interactive Mode in Python: - tab window button and search idle to enter the Python interactive
shell.
➢ Script Mode in Python: - Open any text editor (like Notepad, VSCode, etc.) and create a new file
called hello_world.py.
• Save the file and run it in the terminal or command prompt by navigating to the directory
where the file is saved and executing:
Output: -
4
Roll no.-1323472 BCA-406
Practical-02
To write a python program that takes in command line arguments as input and
print the number of arguments.
Source code: -
Import sys
Output: -
5
Roll no.-1323472 BCA-406
Practical-03
Write a python program to illustrate the various functions of math module.
Source Code: -
import math
# 1. Math Constants
print("Math Constants:")
print(f"pi: {math.pi}") # Value of pi
print(f"e: {math.e}") # Value of e (Euler's number)
print(f"tau: {math.tau}") # Value of tau (2 * pi)
print(f"inf: {math.inf}") # Positive infinity
print(f"nan: {math.nan}") # Not a number (NaN)
print()
# 3. Trigonometric Functions
print("Trigonometric Functions:")
angle_rad = math.radians(45) # Convert 45 degrees to radians
print(f"sin(45 degrees in radians): {math.sin(angle_rad)}") # Sine of angle
print(f"cos(45 degrees in radians): {math.cos(angle_rad)}") # Cosine of angle
print(f"tan(45 degrees in radians): {math.tan(angle_rad)}") # Tangent of angle
print(f"degrees({math.pi / 4} radians): {math.degrees(math.pi / 4)}") # Convert radians to degrees
print()
# 4. Logarithmic Functions
print("Logarithmic Functions:")
print(f"log(10): {math.log(10)}") # Natural logarithm (base e)
print(f"log10(100): {math.log10(100)}") # Logarithm with base 10
print(f"log2(16): {math.log2(16)}") # Logarithm with base 2
print()
# 6. Hyperbolic Functions
print("Hyperbolic Functions:")
print(f"sinh(1): {math.sinh(1)}") # Hyperbolic sine
print(f"cosh(1): {math.cosh(1)}") # Hyperbolic cosine
print(f"tanh(1): {math.tanh(1)}") # Hyperbolic tangent
print()
6
Roll no.-1323472 BCA-406
# 7. Rounding Functions
print("Rounding Functions:")
print(f"floor(4.7): {math.floor(4.7)}") # Greatest integer less than or equal to x
print(f"ceil(4.7): {math.ceil(4.7)}") # Smallest integer greater than or equal to x
print(f"trunc(4.7): {math.trunc(4.7)}") # Truncate the decimal part
print(f"round(4.7): {round(4.7)}") # Round to the nearest integer
print()
# 9. Special Functions
print("Special Functions:")
print(f"gamma(5): {math.gamma(5)}") # Gamma function (n-1)!
print(f"lgamma(5): {math.lgamma(5)}") # Logarithm of the absolute value of the Gamma function
7
Roll no.-1323472 BCA-406
Output: -
8
Roll no.-1323472 BCA-406
Practical-04
Write a menu driven program in python to calculate the area of different shapes using
a while loop.
Source code: -
import math
def calculate_area_of_circle(radius):
return math.pi * radius ** 2
def calculate_area_of_square(side):
return side ** 2
def menu():
while True:
print("\nMenu:")
print("1. Calculate Area of Circle")
print("2. Calculate Area of Rectangle")
print("3. Calculate Area of Triangle")
print("4. Calculate Area of Square")
print("5. Exit")
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '1':
radius = float(input("Enter the radius of the circle: "))
area = calculate_area_of_circle(radius)
print(f"The area of the circle is: {area:.2f}")
elif choice == '2':
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = calculate_area_of_rectangle(length, width)
print(f"The area of the rectangle is: {area:.2f}")
9
Roll no.-1323472 BCA-406
Output: -
10
Roll no.-1323472 BCA-406
Practical-05
Write a program in python to create a list and apply all the operation applicable for
the list.
Source code: -
# Create a list
my_list = [10, 20, 30, 40, 50]
print("Initial List:", my_list)
11
Roll no.-1323472 BCA-406
Output: -
12
Roll no.-1323472 BCA-406
Practical-06
Write a program in python to create a tuple and apply all the operation applicable for
the list. Also show that tuples are immutable.
Source Code: -
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
13
Roll no.-1323472 BCA-406
# Attempting list operations on tuple (which will fail)
print("\n\nTrying to Modify Tuple (This will cause an error)")
try:
my_tuple[0] = 10 # Tuples do not support item assignment
except TypeError as e:
print("Error:", e)
try:
my_tuple.append(6) # Tuples do not support append
except AttributeError as e:
print("Error:", e)
try:
my_tuple.remove(3) # Tuples do not support remove
except AttributeError as e:
print("Error:", e)
14
Roll no.-1323472 BCA-406
Output: -
15
Roll no.-1323472 BCA-406
Practical-07
Write a program in python to create a Dictionary and apply all the operation
applicable for the list.
Source code: -
# Create a dictionary with list values
my_dict = {
"numbers": [1, 2, 3, 4, 5],
"fruits": ["apple", "banana", "cherry"],
"letters": ["a", "b", "c", "d"]
}
16
Roll no.-1323472 BCA-406
Output: -
17
Roll no.-1323472 BCA-406
Practical-08
Write a program in python for reading and writing data on a external file.
Source code: -
# File name to work with
file_name = "Ankitsingh.txt"
# Function to write data to a file
def write_to_file():
with open(file_name, 'w') as file:
file.write("Hello! This is a test file.\n")
file.write("This file contains some sample text.\n")
file.write("Python file handling is easy!\n")
print("Data has been written to", file_name)
18
Roll no.-1323472 BCA-406
Practical-09
Write a program in python to create a class and apply following concepts of Object-
Oriented Programming
I. Inheritance
II. Function Overloading
III. Operator Overloading
Source code: -
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Derived Class using Inheritance
class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age) # Calling constructor of Person
self.roll_number = roll_number
19
Roll no.-1323472 BCA-406
# Main Code
if __name__ == "__main__":
# Creating objects
student1 = Student("Ankit Singh", 20, 431)
student2 = Student("Akash", 22, 198)
# Demonstrating Inheritance
print("Student 1 Details:")
student1.display()
Output: -
20
Roll no.-1323472 BCA-406
Practical-10
Develop a Calculator (GUI Interface) using Tkinter in Python.
Source code: -
import tkinter as tk
def click(event):
text = event.widget.cget("text")
if text == "=":
try:
result = eval(str(entry.get()))
entry.delete(0, tk.END)
entry.insert(tk.END, result)
except Exception as e:
entry.delete(0, tk.END)
entry.insert(tk.END, "Error")
elif text == "C":
entry.delete(0, tk.END)
else:
entry.insert(tk.END, text)
# Main Window
root = tk.Tk()
root.geometry("300x400")
root.title("Calculator")
root.resizable(0, 0)
# Entry Widget
entry = tk.Entry(root, font="Arial 20", borderwidth=5, relief="ridge", justify="right")
entry.pack(fill=tk.BOTH, ipadx=8, pady=10, padx=10)
# Buttons layout
buttons = [
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['0', '.', '=', '+'],
['C']
]
for row in buttons:
frame_row = tk.Frame(button_frame)
frame_row.pack(expand=True, fill="both")
for btn_text in row:
button = tk.Button(frame_row, text=btn_text, font="Arial 18", borderwidth=2, relief="ridge")
button.pack(side="left", expand=True, fill="both")
button.bind("<Button-1>", click)
root.mainloop()
21
Roll no.-1323472 BCA-406
Output: -
22
Roll no.-1323472 BCA-406
Practical-11
Write a program in python for connecting to a Database. Perform insertion, deletion
and updation operation in the database.
Source code: -
import sqlite3
# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL
)
''')
conn.commit()
# Inserting students
insert_student("Ankit", 20)
insert_student("Akash", 22)
# Updating a student
update_student(1, "Ankit Singh Rajput", 21)
# Deleting a student
delete_student(2)
23
Roll no.-1323472 BCA-406
import sqlite3
# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL
)
''')
conn.commit()
# Updating a student
update_student(1, "Ankit Singh Rajput", 21)
# Deleting a student
delete_student(2)
24
Roll no.-1323472 BCA-406
Output: -
25
Roll no.-1323472 BCA-406
Practical-12
Develop a Restaurant Management (GUI Interface) using Tkinter in Python.
Source code: -
import tkinter as tk
from tkinter import messagebox
def calculate_total():
total = 0
try:
total += int(e_burger.get()) * 50
total += int(e_pizza.get()) * 150
total += int(e_drinks.get()) * 40
total += int(e_fries.get()) * 30
label_total.config(text=f"Total: ₹{total}")
except ValueError:
messagebox.showerror("Error", "Please enter valid numbers!")
def clear_all():
e_burger.delete(0, tk.END)
e_pizza.delete(0, tk.END)
e_drinks.delete(0, tk.END)
e_fries.delete(0, tk.END)
label_total.config(text="Total: ₹0")
def exit_app():
root.destroy()
# Main Window
root = tk.Tk()
root.title("Restaurant Management System")
root.geometry("400x450")
root.resizable(False, False)
# Title Label
title_label = tk.Label(root, text="Welcome to Restaurant", font=("Arial", 18, "bold"))
title_label.pack(pady=10)
# Menu Items
label_burger = tk.Label(frame_menu, text="Burger (₹50)", font=("Arial", 14))
label_burger.grid(row=0, column=0, pady=5)
e_burger = tk.Entry(frame_menu, width=5, font=("Arial", 14))
e_burger.grid(row=0, column=1, pady=5)
26
Roll no.-1323472 BCA-406
e_drinks = tk.Entry(frame_menu, width=5, font=("Arial", 14))
e_drinks.grid(row=2, column=1, pady=5)
# Total Label
label_total = tk.Label(root, text="Total: ₹0", font=("Arial", 16, "bold"))
label_total.pack(pady=10)
# Buttons
frame_buttons = tk.Frame(root)
frame_buttons.pack(pady=10)
root.mainloop()
Output: -
27