0% found this document useful (0 votes)
75 views34 pages

Python RECORD LAB

Uploaded by

modmalar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
75 views34 pages

Python RECORD LAB

Uploaded by

modmalar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 34

CMS COLLEGE OF SCIENCE & COMMERCE

(AUTONOMOUS)
(Affiliated to Bharathiar University, An ISO Certified Institution, Reaccredited at the
“A+” level with CGPA of 3.53 out of 4 by NAAC)
COIMBATORE – 641 049

DEPARTMENT OF COMPUTER SCIENCE


BATCH: 2023-2025

PRACTICAL RECORD
PYTHON PROGRAMMING LAB

I M.Sc COMPUTER SCIENCE


MARCH 2024
CMS COLLEGE OF SCIENCE & COMMERCE
(AUTONOMOUS)

COIMBATORE – 641 049

REGISTER. NO

BAT25

Certified that this is the Bonafide record work done by Mr/Ms______________


of the First year M.Sc (CS) during the Academic year 2023 – 2024.

………………………… …………………………
Staff In-Charge HOD

Submitted for the Practical Examination held on ____________________ at


CMS College of Science and Commerce, Coimbatore – 641 049.

………………………… …………………………...
Internal Examiner External Examiner
INDEX

PAGE
SL.NO DATE TITLE SIGNATURE
NO

IMPLEMENT THE CONCEPT OF


01
OBJECTS AND CLASSES

TO PERFORM THE OPERATIONS


02
WITH LIST OF INTEGERS

IMPLEMENT A DICTIONARY
03
EXAMPLE

04 IMPLEMENT LIST AND TUPLE

A FUNCTION WITH PARAMETER


05
PASSING TECHNIQUE

IMPLEMENT RECURSIVE
06
FUNCTION

07 IMPLEMENT FILE OBJECTS

IMPLEMENT THREADS AND


08
PROCESSES

IMPLEMENT THE CONCEPT OF


09
CLASS WITH INHERITANCE

PYTHON SCRIPT FOR DATABASE


10
ACCESS IMPLEMENTATION
IMPLEMENT THE CONCEPT OF OBJECTS AND CLASSES

AIM:
To implement the concept of Objects and Classes

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Define a Class and declare the information required
STEP 3: Declare objects to be retrieved
STEP 4: Calculate the Grade to be declared
STEP 5: Repeat Step 4 as per the requirement
STEP 6: Retrieve Grade as per the student details
STEP 7: Save and run the program
STEP 8: Print the result
STEP 9: Stop
PROGRAM:
class student:
def __init__(self, name, grade):
self.name=name
self.grade=grade
def display_student_info(self):
print("Name:{self.name}")
print("Grade:{self.grade}")
def get_grade_points(self):
if self.grade=="A":
return 4.0
elif self.grade=="B":
return 3.0
elif self.grade=="C":
return 2.0
elif self.grade=="D":
return 1.0
else:
return 0.0
def is_passing(self):
return self.get_grade_points()>=2.0
student_1=student("john doe","A")
student_2=student("john doe","B")
print(student_1.get_grade_points())
print(student_2.get_grade_points())
print(student_1.is_passing())
print(student_2.is_passing())
OUTPUT:

RESULT: The given program is executed and verified successfully.


PERFORM THE OPERATIONS WITH THE LIST OF INTEGERS

AIM:
To perform the operations with the list of Integers

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Input the list of numbers as num
STEP 3: Declare the Addition operations to be performed with num in numbers
STEP 4: Repeat step 3 for required operations with num in numbers
STEP 5: Save and run the program
STEP 6: Print the result
STEP 7: Stop
PROGRAM:
numbers=[1,2,3,4,5]
#Addition
result=[num+2 for num in numbers]
print("Addition result:",result)
#Subtraction
result=[num-2 for num in numbers]
print("Subtraction result:",result)
#Multiplication
result=[num*2 for num in numbers]
print("Multiplication result:",result)
#Division
result=[num/2 for num in numbers]
print("Division result:",result)
#Greater than
result=[num>2 for num in numbers]
print("Greater than result:",result)
#Less than
result=[num<2 for num in numbers]
print("Less than result:",result)
#Equl to
result=[num==2 for num in numbers]
print("Equl to result:",result)
#Not equl to
result=[num!=2 for num in numbers]
print("Not equl to result:",result)
OUTPUT:

RESULT: The given program is executed and verified successfully.


IMPLEMENT A DICTIONARY EXAMPLE

AIM:
To implement a Dictionary example

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Create a dictionary initially named data
STEP 3: Create another dictionary to be sorted form initially named data
STEP 4: Iterate step 2 and step 3 as per the number of data to be added in dictionary
STEP 5: Store value in sorted(key)
STEP 6: Save and run the Program
STEP 7: Print the result
STEP 8: Stop
PROGRAM:
myDict = {'muthu' : [50, 60, 70, 80, 90], 'shaja' : [60, 74, 60, 51, 91],}
print("Initially the dictionary is " + str(myDict))

sortedDict = dict()
for key in sorted(myDict):
sortedDict[key] = sorted(myDict[key])
print("Dictionary after sort of key and list value : " + str(sortedDict))
OUTPUT:

RESULT: The given program is executed and verified successfully.


IMPLEMENT LIST AND TUPLES

AIM:
To implement list and tuples

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Create list of products
STEP 3: Read item from user to check the availability
STEP 4: Check if item in products, then go to Step 5, otherwise Step 6
STEP 5: Print the available item
STEP 6: If print item is not available then execute Step 7
STEP 7: Read the Choice (Y/N)
STEP 8: Check if choice==’Y’, then proceed with Step 9, otherwise Step 12
STEP 9: Read the item to be added
STEP 10: Append the item to the list of products
STEP 11: Save and run the Program
STEP 12: Print the Result
STEP 13: Stop
PROGRAM:
products=['keyboard','mouse','processor','speaker','web camera']
item=input("Enter the item to check the availability")
if item in products:
print("Yes, the item",item,"is available")
else:
print("Sorry the item",item,"is not available")
print("Do you want to add the items in the list")
choice=input("Enter your choice as y/n")
if choice=='y':
add=input("enter the item to be added to the list:")
products.append(add)
else:
print("**HAVE A NICE DAY**")
print(products)
OUTPUT:

RESULT: The given program is executed and verified successfully.


CREATE A FUNCTION WITH PARAMETER PASSING TECHNIQUE

AIM:
To create a function with Parameter passing Technique

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Input a string length as len to be retrieved
STEP 3: Input list of numbers to be multiplied
STEP 4: Get the Sum of elements from the list declared
STEP 5: Save and run the Program
STEP 6: Print the result
STEP 7: Stop
PROGRAM:

def string_length(string):
return len(string)

def multiply_numbers(x,y):
return x*y

def sum_list_elements(st):
return sum(st)

string='Hello,world!'
string_length_result = string_length(string)
print("The length of the string '{}' is {}.".format(string,string_length_result))
x=5
y=7
multiply_numbers_result = multiply_numbers(x,y)
print("The product of {} and {} is {}.".format(x,y,multiply_numbers_result))
st = [1,2,3,4,5]
sum_list_elements_result = sum_list_elements(st)
print("The sum of the elements in the list {} is {}.".format(st,sum_list_elements_result))
OUTPUT:

RESULT: The given program is executed and verified successfully.


IMPLEMENT RECURSIVE FUNCTION

AIM:
To implement recursive function

ALGORITHM:
6.1:
STEP 1: Open a new project and Start
STEP 2: Define binomial co-efficient (n, k)
STEP 3: Check if input is 0, then return 1
STEP 4: Else return binomial co-efficient (n-1, k-1)
STEP 5: Define Fibonacci (n)
STEP 6: Check if n is 0, then return 0
STEP 7: Else return Fibonacci (n-1) + Fibonacci (n-2)
STEP 8: Save and run the Program
STEP 9: Print the result
STEP10: Stop

6.2:
STEP 1: Open a new project and Start
STEP 2: Read a number as num
STEP 3: Assign factorial X
STEP 4: If X==1proceed with Step 6, otherwise Step 5
STEP 5: Else X*fact(X-1)
STEP 6: Save and run the program
STEP 7: Print the result
STEP 8: Stop
PROGRAM:
6.1:

def binomial_coefficient(n,k):
if k == 0 or k ==n:
return 1
else:
return binomial_coefficient(n-1,k-1)+binomial_coefficient(n-1,k)
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)

n = int(input("Enter a value for n:"))


k = int(input("Enter a value for k:"))
print("Binomial Coefficient: ",binomial_coefficient(n,k))
n = int(input("Enter a value for n:"))
print("Fibonacci Sequence:",fibonacci(n))

6.2:

def factorial(X):
if X == 1:
return 1
else:
return(X * factorial(X-1))
print(factorial(4))
OUTPUT:

6.1:

6.2:

24

RESULT: The given program is executed and verified successfully.


IMPLEMENT FILE OBJECTS

AIM:
To implement File Objects

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Create an empty file to store employee details, for i in range (num_emp)
STEP 3: To calculate the required information of employee, use the specific formula
STEP 4: To display the entered details in employee file, for 1 in f (file_name)
STEP 5: Save and run the Program
STEP 6: Print the result
STEP 7: Stop
PROGRAM:
def create_emp_file(num_emp):
with open('employee.txt','w') as f:
for i in range(num_emp):
name = input(f"Enter Name of employee {i+1} : ")
eid = input(f"Enter ID of employee {i+1} : ")
des = input(f"Enter Designation of employee {i+1} : ")
basic = float(input(f"Enter basic salary of employee {i+1} : "))

da = 0.5 * basic
pf = 0.12 * (basic + da)
hra = 1000
gross = basic + da + hra
net = gross - pf
emp = (name, eid, des, basic, da, hra, pf, gross, net)

f.write(str(emp) + "\n")
return 'employee.txt'

def dis_emp_file(file_name):
with open(file_name, 'r') as f:
for l in f:
employee_str = l.strip()
employee = eval(employee_str)
print("Name :", employee[0])
print("ID :", employee[1])
print("Designation :", employee[2])
print("Basic Salary :", employee[3])
print("DA :", employee[4])
print("HRA :", employee[5])
print("PF :", employee[6])
print("Gross Salary :", employee[7])
print("Net Salary :", employee[8])
print()

x = int(input("Enter number of entries: "))


file_name = create_emp_file(x)
dis_emp_file(file_name)
OUTPUT:

RESULT: The given program is executed and verified successfully.


IMPLEMENT THREADS AND PROCESSES

AIM:
To implement Threads and Processes

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Define a function [Start/Finish] to be executed by a thread worker_thread():
STEP 3: Define a function [Start/Finish] to be executed by a process worker_process():
STEP 4: Create a new thread and start the same
STEP 5: Create a new process and start the same
STEP 6: Wait for the thread and process to finish thread.join()
STEP 7: Save and run the Program
STEP 8: Print the result
STEP 9: Stop
PROGRAM:

import threading import multiprocessing import time

# Define a function that will be executed by a thread def worker_thread():


print("Worker thread started") time.sleep(5) # simulate some work print("Worker thread
finished")

# Define a function that will be executed by a process def worker_process():


print("Worker process started") time.sleep(5) # simulate some work print("Worker process
finished")

# Create a new thread and start it


thread = threading.Thread(target=worker_thread) thread.start()

# Create a new process and start it


process = multiprocessing.Process(target=worker_process) process.start()

# Wait for the thread and process to finish thread.join()


process.join() print("Done")
OUTPUT:

RESULT: The given program is executed and verified successfully.


IMPLEMENT CLASS WITH INHERITANCE

AIM:
To implement Class with Inheritance

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Define a Class student and enter the information required
STEP 3: Define a Class CIA marks and enter the information required
STEP 4: Define a Class ESE marks and enter the information required
STEP 5: Inherit the above classes in new Class Marksheet
STEP 6: To calculate the required information in of student, use the specific formula
STEP 7: Save and run the Program
STEP 8: Enter the student details in marksheet(self)
STEP 9: Print the result
STEP 10: Stop
PROGRAM:
class Student:
def _init_(self, name, roll_number):
self.name = name
self.roll_number = roll_number

class CIAMarks:
def _init_(self, cia_marks):
self.cia_marks = cia_marks

class ESEMarks:
def _init_(self, ese_marks):
self.ese_marks = ese_marks

class Marksheet(Student, CIAMarks, ESEMarks):


def _init_(self, name, roll_number, cia_marks, ese_marks):
Student._init_(self, name, roll_number)
CIAMarks._init_(self, cia_marks)
ESEMarks._init_(self, ese_marks)

def calculate_total_marks(self):
return self.cia_marks + self.ese_marks

def calculate_percentage(self):
total_marks = self.calculate_total_marks()
percentage = (total_marks / 100) * 100
return round(percentage, 2)

def print_marksheet(self):
print("Name:", self.name)
print("Roll Number:", self.roll_number)
print("CIA Marks:", self.cia_marks)
print("ESE Marks:", self.ese_marks)
print("Total Marks:", self.calculate_total_marks())
print("Percentage:", self.calculate_percentage(), "%")

name = input("Enter student name: ")


roll_number = input("Enter student roll number: ")
cia_marks = int(input("Enter CIA marks: "))
ese_marks = int(input("Enter ESE marks: "))

student = Marksheet(name, roll_number, cia_marks, ese_marks)


student.print_marksheet()
OUTPUT:

RESULT: The given program is executed and verified successfully.


PYTHON SCRIPT FOR DATABASE ACCESS IMPLEMENTATION

AIM:
To create Python Script for Database access implementation

ALGORITHM:
STEP 1: Open a new project and Start
STEP 2: Establish a connection to the database
STEP 3: Create a cursor object, cursor ()
STEP 4: Execute a SQL query to create a table, create_table_query
STEP 5: Execute SQL queries to insert data into the table
STEP 6: Commit the changes to the database, cnx.commit()
STEP 7: Execute a SQL query to retrieve data from the table. Select_query
STEP 8: Retrieve the query result and close the cursor and connection, close ()
STEP 9: Save and run the Program
STEP 10: Print the result
STEP 11: Stop
PROGRAM:
import mysql.connector

# Establish a connection to the database


cnx = mysql.connector.connect(user='username', password='password', host='hostname',
database='databasename')

# Create a cursor object cursor = cnx.cursor()

# Execute a SQL query to create a table create_table_query = """


CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT PRIMARY
KEY, name VARCHAR(255),
age INT, grade FLOAT); """
cursor.execute(create_table_query)

# Execute SQL queries to insert data into the table


insert_query1 = "INSERT INTO students (name, age, grade) VALUES ('Jerome', 30, 8.5)"
insert_query2 = "INSERT INTO students (name, age, grade) VALUES ('Shajan', 21, 7.5)"
cursor.execute(insert_query1)
cursor.execute(insert_query2)

# Commit the changes to the database cnx.commit()

# Execute a SQL query to retrieve data from the table select_query = "SELECT * FROM
students" cursor.execute(select_query)

# Retrieve the query result result = cursor.fetchall() print(result)

# Close the cursor and connection cursor.close()


cnx.close()
OUTPUT:

| id | name | age | grade |


|----|-----------|------|---------|
| 1 | Jerome | 30 | 8.5 |
| 2 | Shajan | 21 | 7.5 |

[(1, 'Jerome', 30, 8.5), (2, 'Shajan', 21, 7.5)]

RESULT: The given program is executed and verified successfully.

You might also like