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

Python Manual

The program demonstrates method overriding by defining a Father class with a method, and a Son class that inherits from Father but overrides the method. When the overridden method from the Son class is called, it will execute the Son's version instead of the Father's version, showing how subclasses can override methods from superclasses in Python.

Uploaded by

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

Python Manual

The program demonstrates method overriding by defining a Father class with a method, and a Son class that inherits from Father but overrides the method. When the overridden method from the Son class is called, it will execute the Son's version instead of the Father's version, showing how subclasses can override methods from superclasses in Python.

Uploaded by

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

K.S.

RANGASAMY COLLEGE OF ARTS AND SCIENCE (AUTONOMOUS)

TIRUCHENGODE

DEPARTMENT OF COMPUTER SCIENCE (UG)

V SEMESTER

BATCH (2021-2023)

DSC PRACTICAL V: PYTHON PROGRAMMING LAB

SUBJECT CODE: 21UCSMP501

LAB MANUAL

Prepared by Reviewed & Approved by Issued by


HOD PRINCIPAL
A.Venugopal Dr.K.M.Prabu Sankarlal Dr. V.Radhakrishnan
K.Thilakavalli
P.Suganya
PAGE
S.NO PROGRAM TITLE
NO

1 a. Write a python program to add two numbers


b. Write a python program to demonstrate basic data types in python.

2 Program to perform different arithmetic operations on numbers in


python
3 a.Program to calculate Factorial of Number Using Recursion
b.Program to perform filter() to filter only even numbers from given
the list

4 a. Program to save image using Scipy


b. Program to create Numpy array from the image
5 Program to perform various operations on list, Tuples & dictionary
6 Program to override super class constructor and method in subclass
7 Program to handle multiple exceptions.
8 Program to know whether a file exists or not.
9 Program to read a CSV file consists of students marks statements and
write in another CSV file with total, average and grade.
10 Program to retrieve all rows from employee table and display the
column values in tabular column in MYSQL.
1. a) Write a python program to add two numbers
Aim:

To write a python program to add two numbers.

Procedure:
Step 1: Start a process.

Step 2: Read the First number.

Step 3: Read the Second number.

Step 4: Add two numbers

Step 5: Display the sum

Step 6: Stop the process.

Program:

# program to add two numbers

number1 = input("First number: ")


number2 = input("\nSecond number: ")

# Adding two numbers


# User might also enter float numbers
sum = float(number1) + float(number2)

# Display the sum


# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1, number2, sum))

Output:

First number: 10

Second number: 30

The sum of 10 and 30 is 40.0


1.(b) Write program to demonstrate basic data types in python
Aim:

To write a python program to demonstrate basic data types

Procedure:
Step 1: Start a process.

Step 2: Read the a, b, c

Step 3: Display the data type of a, b and c

Step 4: Create the list with the values

Step 4: Display the list[0],[2].

Step 5: Create a tuple with the use of list

Step 6: Display the tuple.

Step 7: Stop the process.

Program:
# Python program to demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a List with the use of multiple values


List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Tuple with the use of list


list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

Output:

Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>


String with the use of Single Quotes:
Welcome to the Geeks World

List containing multiple values:


Geeks
Geeks

Tuple using List:


(1, 2, 4, 5, 6)

2. Program to different arithmetic operations on numbers in python.

Aim:

To write a python program to different operations on numbers

Procedure:
Step 1: Start a process.

Step 2: Read the first and second number

Step 3: Add two numbers and store sum

Step 4: subtract two numbers and store min

Step 5: Multiply two numbers and store mul

Step 6: Divide two numbers and store div

Step 7: Display the sum,min,mul,div

Step 8: Stop the process.

Program:

# Store input numbers:


num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)
# Subtract two numbers
min = float(num1) - float(num2)
# Multiply two numbers
mul = float(num1) * float(num2)
#Divide two numbers
div = float(num1) / float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

# Display the subtraction


print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))
# Display the multiplication
print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))
# Display the division
print('The division of {0} and {1} is {2}'.format(num1, num2, div))

Output:
Enter first number: 10
Enter second number: 20
The sum of 10 and 20 is 30.0
The subtraction of 10 and 20 is -10.0
The multiplication of 10 and 20 is 200.0
The division of 10 and 20 is 0.5

3. a) Program to calculate Factorial of Number Using Recursion

Aim:

To write a python program to calculate Factorial of Number Using Recursion

Procedure:
Step 1: Start a process.

Step 2: Read the number

Step 3: If the number is 1 then display 1.


Step 4: If the number is greater than 1 then calculate number*(number-1) and display the
value

Step5: If the number is less than 0 then display Sorry, factorial does not exist for negative
numbers

Step 6: Stop the process.

Program:

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

Output:
Enter a number: 5
The factorial of 5 is 120
3.b) Program to perform filter() to filter only even numbers from given the list
Aim:

To write a python program using filter() to filter only even numbers from given the
list.

Procedure:
Step 1: Start a process.

Step 2: Read the numbers 1 to 10

Step 3: If the number is passed to check_even function returns true

Step 4: Then filter the even numbers and convert to list format

Step 5: Display the list

Step 6: Stop the process.

Program:
# returns True if the argument passed is even

def check_even(number):
if number % 2 == 0:
return True

return False

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# if an element passed to check_even() returns True, select it


even_numbers_iterator = filter(check_even, numbers)

# converting to list
even_numbers = list(even_numbers_iterator)

print(even_numbers)

Output:
[2, 4, 6, 8, 10]
4.(a) Program to save image using Scipy
Aim:

To write a python program to save image using Scipy


Procedure:
Step 1: Start a process.

Step 2: Read a image of raccoon face

Step 3: Save the image

Step 4: Display the image

Step 5: Stop the process.

Program:
from scipy import misc
import imageio
import matplotlib.pyplot as plt

# reads a raccoon face


face = misc.face()

# save the image


imageio.imsave('raccoon.png', face)

plt.imshow(face)
plt.show()

Output:
4.(b) program to create Numpy array from the image
Aim:

To write a python program to create Numpy array from the image


Procedure:
Step 1: Start a process.

Step 2: Read a image of raccoon face

Step 3: Save the image

Step 4: Display the image

Step 5: Stop the process.

Program:
from scipy import misc
import imageio
import matplotlib.pyplot as plt

img = imageio.imread('raccoon.png')

print(img.shape)
print(img.dtype)

plt.imshow(img)
plt.show()

Output:
(768, 1024, 3)
5. Program to perform various operations on List, Tuples, Set & dictionary

Aim:

To write a python program to perform various operations on List, Tuples, Set & dictionary

Procedure:
Step 1: Start a process.

Step 2: Add the 5,10 to the list and pop one element to list

Step 3: Display the list.

Step 4: Add the 5,10 to the set and remove 5 from the set

Step 5: Tuple one element

Step 6: Adding key value of 5,10 and Display the dictionary

Step 7: Removing one key pair value

Step 8: Stop the process.

Program:
# use of list, tuple, set and dictionary
# Lists
l = []
# Adding Element into list
l.append(5)
l.append(10)
print("Adding 5 and 10 in list", l)
# Popping Elements from list
l.pop()
print("Popped one element from list", l)
print()
# Set
s = set()
# Adding element into set
s.add(5)
s.add(10)
print("Adding 5 and 10 in set", s)
# Removing element from set
s.remove(5)
print("Removing 5 from set", s)
print()
# Tuple
t = tuple(l)
# Tuples are immutable
print("Tuple", t)
print()
# Dictionary
d = {}
# Adding the key value pair
d[5] = "Five"
d[10] = "Ten"
print("Dictionary", d)
# Removing key-value pair
del d[10]
print("Dictionary", d)

Output:
Adding 5 and 10 in list [5, 10]
Popped one element from list [5]
Adding 5 and 10 in set {10, 5}
Removing 5 from set {10}
Tuple (5,)
Dictionary {5: 'Five', 10: 'Ten'}
Dictionary {5: 'Five'}
6. Program to override super class constructor and method in subclass
Aim:

To write a python program to override super class constructor and method in subclass

Procedure:
Step 1: Start a process.

Step 2: The Son class inherits the Father class

Step 3: class Father and class Son have the same method name

Step 4: The same method names in the base and inheritance classes. We call method
overriding.

Step 5: Writing constructor in base and inherited class we call constructor overriding.

Step 6: And finally display Son’s method

Step7: Stop the process.

Program:
#Overriding the base class constructor and method in sub class
class Father:
def __init__(self):
self.property=80000.00
def display_property(self):
print('Father\'s property=',self.property)
class Son(Father):
def __init__(self):
self.property=20000.00

def display_property(self):
print('Child\'s property=',self.property)
#create sub class instance and display father's property
s= Son()
s.display_property()
Output:
Child's property= 20000.0

7. Program to handle multiple exceptions.


Aim:

To write a python program to handle multiple exceptions.

Procedure:
Step 1: Start a process.

Step 2: Read the values in the list

Step 3: While looping check whether the exception is caught

Step 4: Then display the exception otherwise display the value

Step5: Stop the process.

Program:
# iterable object
mylist = [-1, 2, 0, 4, 0]
# for loop
for i in mylist:
# Python catch multiple exceptions
try:
# raise when divide by zero
print("thedivision is:", 10/i)
# this block will be executed if error occurs
except:
# raise an error
print("Error occurs while dividing")

Output

thedivision is: -10.0


thedivision is: 5.0
Error occurs while dividing
thedivision is: 2.5
Error occurs while dividing
8. Program to know whether a file exists or not.

Aim:

To write a python program to know whether a file exists or not.

Procedure:
Step 1: Start a process.

Step 2: Checking if file exists and then reading data

Step 3: Open the file and display the contents of file

Step 4: If the file is not exists and display yourfile.txt does not exist

Step5: Stop the process.

Program:

#checking if file exists and then reading data


import os, sys
#open the file for reading data
fname=input('Enter filename:')

if os.path.isfile(fname):
f=open(fname,'r')
else:
print(fname+'doesnot exist')
sys.exit()

#read strings from the file


print('The file contents are:')
str=f.read()
print(str)
#closing the file
f.close

Output:

Enter filename:myfile.txt
The file contents are:
Welcome to Python Programming
Enter filename:yourfile.txt
yourfile.txtdoesnot exist
9. Program to read a CSV file consists of students marks statements and write in
another CSV file with total, average and grade.

Aim:

To write a python program to read a CSV file consists of students marks statements
and write in another CSV file with total, average and grade.

Procedure:
Step 1: Create a CSV file manually with header (“Reg. No.”,
“Name”,”Mark1”,”Mark2”,”Mark3”,)
Step 2: Enter the values in the CSV file manually
Step 3: Open the CSV file and read its content
Step 4: Calculate the total, average and grade using the values read
Step 5: Create list and store the values read from the file and calculated values
Step 6: Create a new CSV file
Step 7: Write all the content to a new CSV file
Step 8: Close the file
Program
import csv

def calculate_grade(average):
if average >= 90:
return 'A'
elif average >= 80:
return 'B'
elif average >= 70:
return 'C'
elif average >= 60:
return 'D'
else:
return 'F'

def process_marks(input_file, output_file):


with open(input_file, 'r') as file:
reader = csv.reader(file)
header = next(reader) # Skip the header row
data = [row + [int(row[1]) + int(row[2]) + int(row[3])] for row in reader]

with open(output_file, 'w', newline='') as file:


writer = csv.writer(file)
writer.writerow(header + ['Total', 'Average', 'Grade'])
for row in data:
average = row[4] / 3
grade = calculate_grade(average)
writer.writerow(row + [row[4], average, grade])

print(f"Processed data written to {output_file}")

# Example usage:
input_file = 'C:\Program Files\Python311\marks.csv'
output_file = 'C:\Program Files\Python311\marks_with_grade.csv'
process_marks(input_file, output_file)
Output
CSV Input File Content

Regno Name Mark1 Mark2 Mark3


21UCS0
1 keerthi 45 56 67
21UCS0
2 venu 96 87 87
21UCS0
3 gopal 67 78 89

Mark Mark Averag Grad


Regno Name 1 Mark2 3 Total e e
21UCS0
1 keerthi 45 56 67 168 56 F
21UCS0
2 venu 96 87 87 270 90 A
21UCS0
3 gopal 67 78 89 234 78 C
10. Program to retrieve all rows from employee table and display the column values in
tabular in MYSQL.
Aim:

To write a python program to retrieve all rows from employee table and display the
common values in tabular column in MYSQL.

Procedure:
Step 1: Start a process.

Step 2: Import the necessary modules

Step 3: Connect to the database

Step 4: Execute a SELECT query, Use the cursor's execute () method to execute an SQL
SELECT query to retrieve all rows from the employee table.

Step 5: Fetch the results: Use the cursor's fetchall() method to retrieve all rows returned by
the SELECT query.

Step 6: Process the retrieved data and Close the cursor and the database connection

Step 7: Stop the process.

Program:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="venu"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM employee")

myresult = mycursor.fetchall()
for x in myresult:
print(x)

Output:

(1, 'venu', 'm', 'info Tech')


(2, 'banu', 'f', 'CS')
(3, 'Keerthi', 'm', 'civil')
(4, 'Kiruthikesh', 'm', 'mech')

Result:
The above program has been verified successfully

You might also like