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

Python an Kit

Uploaded by

Irfan Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python an Kit

Uploaded by

Irfan Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Roll no.

-1323472 BCA-406

A
(BCA-406)
Practical File On
Python Programing Lab
BCA-406

Submitted By: Submitted To:


Name: Ankit Kumar Preety Sharma
Class: BCA 4st (F) Assistant Professor

Roll No.: 1323472 MMICT & BM

M.M. Institute of Computer technology & Business Management


Maharishi Markandeshwar (Deemed to be University), Mullana - Ambala, Haryana)
(Established under Section 3 of the UGC Act, 1956)
(Accredited by NAAC with ‘A++)

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

02. To write a python program that takes in command


line arguments as input and print the number of
arguments.
03. Write a python program to illustrate the various
functions of math module.
04. Write a menu driven program in python to
calculate the area of different shapes using a while
loop.
05. [PYTHON COLLECTION]

Write a program in python to create a list and


apply all the operation applicable for the list.

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.
07. Write a program in python to create a Dictionary
and apply all the operation applicable for the list.
08. [FILE HANDLING]

Write a program in python for reading and writing


data on a external file.
09. [OBJECTS AND CLASSES]

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
10. [GUI Programming]

Develop a Calculator (GUI Interface) using Tkinter


in Python.
11. [DATABASE]

Write a program in python for connecting to a


Database. Perform insertion, deletion and updation
operation in the database.
12. Develop a Restaurant Management (GUI
Interface) using Tkinter in Python.

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

Step 1: Install Python

➢ 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:

Step 2: Install Jupyter Notebook

➢ 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.

• Test a simple Python program interactively:

➢ Script Mode in Python: - Open any text editor (like Notepad, VSCode, etc.) and create a new file
called hello_world.py.

• Write your Python code in the script

• 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

# Get the list of command-line arguments


arguments = sys.argv[1:] # Exclude the script name itself

# Count the number of arguments


num_arguments = len(arguments)

# Print the number of arguments


print(f"Number of arguments: {num_arguments}")

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()

# 2. Basic Math Functions


print("Basic Math Functions:")
print(f"sqrt(16): {math.sqrt(16)}") # Square root
print(f"pow(2, 3): {math.pow(2, 3)}") # Power function (2^3)
print(f"fabs(-5.7): {math.fabs(-5.7)}") # Absolute value
print(f"fmod(5, 2): {math.fmod(5, 2)}") # Modulus of floating point numbers
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()

# 5. Factorial, Combinations, and Permutations


print("Factorial, Combinations, and Permutations:")
print(f"factorial(5): {math.factorial(5)}") # Factorial of a number (5!)
print(f"comb(5, 2): {math.comb(5, 2)}") # Number of combinations (5 choose 2)
print(f"perm(5, 2): {math.perm(5, 2)}") # Number of permutations (5P2)
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()

# 8. Other Mathematical Functions


print("Other Mathematical Functions:")
print(f"gcd(12, 15): {math.gcd(12, 15)}") # Greatest common divisor
print(f"hypot(3, 4): {math.hypot(3, 4)}") # Hypotenuse of a right triangle
print(f"isclose(0.1 + 0.2, 0.3): {math.isclose(0.1 + 0.2, 0.3)}") # Test whether two values are close
print(f"modf(4.5): {math.modf(4.5)}") # Return the fractional and integer parts
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_rectangle(length, width):


return length * width

def calculate_area_of_triangle(base, height):


return 0.5 * base * height

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}")

elif choice == '3':


base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = calculate_area_of_triangle(base, height)
print(f"The area of the triangle is: {area:.2f}")

elif choice == '4':


side = float(input("Enter the side length of the square: "))
area = calculate_area_of_square(side)
print(f"The area of the square is: {area:.2f}")

elif choice == '5':


print("Exiting the program...")
break
else:
print("Invalid choice! Please select a valid option.")
menu()

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)

# Append an element to the list


my_list.append(60)
print("After Append:", my_list)

# Insert an element at a specific index


my_list.insert(2, 25)
print("After Insert:", my_list)

# Extend the list with another list


my_list.extend([70, 80])
print("After Extend:", my_list)

# Remove a specific element


my_list.remove(25) # Removes the first occurrence of 25
print("After Remove:", my_list)

# Pop an element (default last element)


popped_element = my_list.pop()
print("After Pop:", my_list)
print("Popped Element:", popped_element)

# Reverse the list


my_list.reverse()
print("After Reverse:", my_list)

# Sort the list


my_list.sort()
print("After Sort (Ascending):", my_list)

# Sort the list in descending order


my_list.sort(reverse=True)
print("After Sort (Descending):", my_list)

# Find the index of an element


index_of_30 = my_list.index(30)
print("Index of 30:", index_of_30)

# Count occurrences of an element


count_of_40 = my_list.count(40)
print("Count of 40:", count_of_40)

# Clear the list


my_list.clear()
print("After Clear:", 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)

# Display original tuple


print("Original Tuple:", my_tuple)

# Accessing elements (Indexing and Slicing - works like a list)


print("\nAccessing Elements:")
print("First Element:", my_tuple[0])
print("Last Element:", my_tuple[-1])
print("Slice [1:4]:", my_tuple[1:4])

# Finding length of the tuple


print("\nLength of Tuple:", len(my_tuple))

# Counting occurrences of an element


print("Count of 2 in Tuple:", my_tuple.count(2))

# Finding the index of an element


print("Index of 4 in Tuple:", my_tuple.index(4))

# Iterating over a tuple


print("\nIterating Over Tuple:")
for item in my_tuple:
print(item, end=" ")

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)

# Converting tuple to list, modifying, and converting back to tuple


print("\nModifying Tuple by Converting to List:")
temp_list = list(my_tuple) # Convert tuple to list
temp_list.append(6) # Modify list
temp_list.remove(2)
new_tuple = tuple(temp_list) # Convert back to tuple
print("Modified Tuple:", new_tuple)

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"]
}

# Display the original dictionary


print("Original Dictionary:")
print(my_dict)

# Append an element to a specific key (like append in list)


my_dict["numbers"].append(6)
print("\nAfter appending 6 to 'numbers':", my_dict)

# Extend a list in a dictionary (like extend in list)


my_dict["fruits"].extend(["mango", "grape"])
print("\nAfter extending 'fruits' with ['mango', 'grape']:", my_dict)

# Insert an element at a specific position (like insert in list)


my_dict["letters"].insert(2, "z")
print("\nAfter inserting 'z' at index 2 in 'letters':", my_dict)

# Remove an element (like remove in list)


my_dict["numbers"].remove(3)
print("\nAfter removing 3 from 'numbers':", my_dict)

# Pop an element from a specific key (like pop in list)


popped_value = my_dict["fruits"].pop(1)
print("\nAfter popping index 1 from 'fruits':", my_dict, "\nPopped Value:", popped_value)

# Reverse the list in a dictionary (like reverse in list)


my_dict["letters"].reverse()
print("\nAfter reversing 'letters':", my_dict)

# Sort a list in a dictionary (like sort in list)


my_dict["numbers"].sort()
print("\nAfter sorting 'numbers':", my_dict)

# Check if a key exists


key = "fruits"
print(f"\nIs '{key}' present in dictionary?:", key in my_dict)
# Iterate over dictionary (like iterating over a list)
print("\nIterating over dictionary keys and values:")
for key, value in my_dict.items():
print(key, ":", value)

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)

# Function to read data from a file


def read_from_file():
print("\nReading data from", file_name)
with open(file_name, 'r') as file:
content = file.read()
print("File Content:\n")
print(content)
# Main execution
if __name__ == "__main__":
write_to_file()
read_from_file()
Output: -

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

# Function Overloading (using default parameters)


def display(self, show_roll_number=True):
if show_roll_number:
print(f"Name: {self.name}, Age: {self.age}, Roll Number: {self.roll_number}")
else:
print(f"Name: {self.name}, Age: {self.age}")

# Operator Overloading: Adding two Student objects (age addition example)


def __add__(self, other):
if isinstance(other, Student):
return self.age + other.age
else:
raise TypeError("Addition only supported between Student instances.")

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()

print("\nStudent 2 Details (without Roll Number):")


student2.display(show_roll_number=False)

# Demonstrating Operator Overloading


print("\nSum of ages of student1 and student2:")
age_sum = student1 + student2 # Calls __add__
print(f"Total Age: {age_sum}")

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)

# Frame for Buttons


button_frame = tk.Frame(root)
button_frame.pack()

# 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

# Connect to a database (or create if it doesn't exist)


conn = sqlite3.connect('student.db')
cursor = conn.cursor()

# 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()

# Function to insert data


def insert_student(name, age):
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", (name, age))
conn.commit()
print("Student inserted successfully!")

# Function to delete data


def delete_student(student_id):
cursor.execute("DELETE FROM students WHERE id = ?", (student_id,))
conn.commit()
print("Student deleted successfully!")

# Function to update data


def update_student(student_id, new_name, new_age):
cursor.execute("UPDATE students SET name = ?, age = ? WHERE id = ?", (new_name, new_age,
student_id))
conn.commit()
print("Student updated successfully!")

# --- Example Usage ---

# 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

# Fetch and display all students


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nStudents in the database:")
for row in rows:
print(row)

# Close the connection


conn.close()

import sqlite3

# Connect to a database (or create if it doesn't exist)


conn = sqlite3.connect('student.db')
cursor = conn.cursor()

# 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()

# Function to insert data


def insert_student(name, age):
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", (name, age))
conn.commit()
print("Student inserted successfully!")

# Function to delete data


def delete_student(student_id):
cursor.execute("DELETE FROM students WHERE id = ?", (student_id,))
conn.commit()
print("Student deleted successfully!")

# Function to update data


def update_student(student_id, new_name, new_age):
cursor.execute("UPDATE students SET name = ?, age = ? WHERE id = ?", (new_name, new_age,
student_id))
conn.commit()
print("Student updated successfully!")
# 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)

24
Roll no.-1323472 BCA-406

# Fetch and display all students


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nStudents in the database:")
for row in rows:
print(row)

# Close the connection


conn.close()

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)

# Frame for menu


frame_menu = tk.Frame(root)
frame_menu.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)

label_pizza = tk.Label(frame_menu, text="Pizza (₹150)", font=("Arial", 14))


label_pizza.grid(row=1, column=0, pady=5)
e_pizza = tk.Entry(frame_menu, width=5, font=("Arial", 14))
e_pizza.grid(row=1, column=1, pady=5)
label_drinks = tk.Label(frame_menu, text="Drinks (₹40)", font=("Arial", 14))
label_drinks.grid(row=2, column=0, 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)

label_fries = tk.Label(frame_menu, text="Fries (₹30)", font=("Arial", 14))


label_fries.grid(row=3, column=0, pady=5)
e_fries = tk.Entry(frame_menu, width=5, font=("Arial", 14))
e_fries.grid(row=3, 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)

btn_total = tk.Button(frame_buttons, text="Total", font=("Arial", 14), padx=10,


command=calculate_total)
btn_total.grid(row=0, column=0, padx=5)

btn_clear = tk.Button(frame_buttons, text="Clear", font=("Arial", 14), padx=10, command=clear_all)


btn_clear.grid(row=0, column=1, padx=5)

btn_exit = tk.Button(frame_buttons, text="Exit", font=("Arial", 14), padx=10, command=exit_app)


btn_exit.grid(row=0, column=2, padx=5)

root.mainloop()
Output: -

27

You might also like