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

PYTHON

Uploaded by

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

PYTHON

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

RECORD NOTE BOOK

2022 - 2023

DHANALAKSHMI SRINIVASAN
COLLEGE OF ENGINEERING
NAVAKKARAI, COIMBATORE-641 105
EXPERIMENTS:

1. Identification and solving of simple real life or scientific or technical problems, and developing flow charts
for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar,
compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two variables,
circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns, pyramid
pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a library/Components of
a car/ Materials required for construction of a building –operations of list & tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language, components of an
automobile, Elements of a civil structure, etc.- operations of Sets & Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy. Matplotlib,
scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to another, word
count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error, voter’s age
validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.

PREPARED BY
CSE DEPT
Ex.No:1 ELECTRICITY BILL GENERATION
Date:

AIM:

Write a Python program to generate an Electricity bill.

ALGORITHM:

Step 1: Start.
Step 2: Get the Input from the user (no of units consumed).
Step 3: Perform the calculations based on consumption of Electricity
By given formula.
Step 4: Print the calculated amount.
Step 5: Stop.

PROGRAM :

units = int(input(" Please enter Number of Units you Consumed : "))


if(units < 50):

amount = units * 2.60


surcharge = 25
elif(units <= 100):
amount = 130 + ((units - 50) * 3.25)
surcharge = 35
elif(units <= 200):
amount = 130 + 162.50 + ((units - 100) * 5.26)
surcharge = 45
else:
amount = 130 + 162.50 + 526 + ((units - 200) * 8.45)
surcharge = 75
total = amount + surcharge print("\
nElectricity Bill = %.2f" %total)

OUTPUT:

Please enter Number of Units you consumed:


150 Electricity Bill = 600.50

RESULT:

Thus the Bill generation for Electricity has been calculated using python programming is
executed and verified successfully.
Ex.No: 2 SUM OF SINE SERIES
Date:

AIM:

Write a Python program to compute a Sum of SINE Series.

ALGORITHM:

Step 1: Start.
Step 2: Get the Input from the user as X degrees and no of terms to be sorted in separate
Arguments.
Step 3: These values are passed to the sine functions as arguments.
Step 4: A sine function is defined and a for loop is used convert degrees to radians and
find the value of each term using the sine expansion formula.
Step 5: Each term is added the sum variable.
Step 6: This continues till the number of terms is equal to the number given by the user.
Step 7: The total sum is printed.

PROGRA
M: import math
def sin(x,n):
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))
math.factorial(2*i+1))*sign
return sine
x=int(input("Enter the value of x in
degrees:")) n=int(input("Enter the number of
terms:")) print(round(sin(x,n),2))

OUTPUT:

Enter the value of x in degrees: 150


Enter the number of terms: 3
0.65

RESULT:

Thus the Computing of SINE series using Numbers has been calculated using python
programming is executed and verified successfully.
EX.NO:3 DATE:
CALCULATING WEIGHT OF MOTORBIKE

AIM:

Write a Python program to calculate the Weight of a Motor Bike using Python
programming.

ALGORITHM:

Step 1: Start.
Step 2: Enter the String Value
Step 3: Print the Original String.
Step 4: Calculate the sum of the Original String
given Step 5: Stop.

PROGRAM:

test_str = 'motorbike'
print("The original string is : " + str(test_str))
sum_dict = {"m" : 5, "o" : 2, "t" : 10,
"r" : 3, "b" : 15, "i" : 4, "k" : 6, "e" : 5}
res = 0
for ele in test_str:
res += sum_dict[ele]
print("The weighted sum : " + str(res))

OUTPUT:

The original string is: motorbike


The weighted sum: 52

RESULT:

Thus the weighted sum of a string is calculated using python programming is executed and
verified successfully.
Ex.No:4 BUBBLE SORT
Date:

AIM:
Write a Python program to find the sorting of numbers using Bubble Sort.

ALGORITHM:

Step 1: Start.
Step 2: Enter the Unsorted Values.
Step 3: Checks the condition for each and every
value. Step 4: Print the sorted vales as output
Step 5: Stop.

PROGRAM:

def bubbleSort(arr):
n = len(arr)
# Traverse through all array
elements for i in range(n-1):
# range(n) also work but outer loop will
# repeat one time more than needed.
# Last i elements are already in
place for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1] :
arr[j], arr[j + 1] = arr[j + 1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90,23]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("% d" % arr[i],end=" ")

OUTPUT:

Sorted array is:


> 56
11 12 22 23 25 34 64 90 56

RESULT:

Thus the sorting of numbers using Bubble sort in python program is executed and
verified successfully.
Ex.No:5 SWAPPING TWO NUMBERS
Date:

AIM:

Write a Python program to swap the two numbers.

ALGORITHM:

Step 1: Start.
Step 2: Enter the first no (X).
Step 3: Enter the Second No (Y).
Step 4: Calculate the no given by using the
expression. Step 5: Print the values.
Step 5: Stop.

PROGRAM:

x = 10
y = 50
x=x+y
y=x-y
x=x-y
print("Value of x:", x)
print("Value of y:", y)

OUTPUT:

Value of x: 50
Value of y: 10

RESULT :

Thus the swapping of two numbers using python programming is executed and verified
Successfully.
Ex.No: 6 CIRCULATE THE VALUES OF N
Date:

AIM:
Write a Python Program to circulate the values of N.

ALGORITHM:

Step 1: Start.
Step 2: Enter the no of values.
Step 3: Enter the Integer no.
Step 4: Calculate the given no to all the list by append and pop.
Step 5: Print the list values.
Step 5: Stop.

PROGRAM:

no_of_terms = int(input("Enter number of values : "))


list1 = []
for val in range(0,no_of_terms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)

OUTPUT:

Enter number of values: 5


Enter integer: 1
Enter integer: 2
Enter integer: 4
Enter integer: 5
Enter integer: 6

Circulating the elements of list [1, 2, 4, 5, 6]


[2, 4, 5, 6, 1]
[4, 5, 6, 1, 2]
[5, 6, 1, 2, 4]
[6, 1, 2, 4, 5]
[1, 2, 4, 5, 6]

RESULT:

Thus the circulation of values to no N using python program is executed and verified
successfully.
Ex.No:7 DISTANCE BETWEEN TWO POINTS
Date:

AIM:

Write a Python Program to find the distance between two points.

ALGORITHM:

Step 1: Start.
Step 2: Enter the first value(X1).
Step 3: Enter the second value(X2).
Step 4: Enter the third value (Y1).
Step 5: Enter the fourth value (Y2).
Step 6: Calculate the results.
Step 7: Print the results.
Step 5: Stop.

PROGRAM :

x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)

OUTPUT:

enter x1 : 15
enter x2 : 35
enter y1 : 25
enter y2 : 45
distance between (15, 35) and (25, 45) is : 28.284271247461902

RESULT:

Thus the program for Distance between two points has been executed and verified
successfully.
Ex.No:8 READ A NUMBER N, PRINT AND COMPUTE THE
Date: SERIES

AIM:

Write a Python Program to read a number of N, to print and to compute the


series of numbers.

ALGORITHM:

Step 1: Start.
Step 2: Enter the number.
Step 3: Calculate the values.
Step 4: Sum the values.
Step 5: Stop.

PROGRAM:

n=int(input("Enter a number: "))


a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()

OUTPUT:

Enter a number: 20
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 210

RESULT:

Thus the program to read a number, print and to compute the number is executed and
verified successfully.
Ex.No:9 PRINT PYRAMID PATTERNS
Date:

AIM:

Write a Python Program to read a number of N, to print and to compute the series of
numbers.

ALGORITHM:

Step 1: Start.
Step 2: Enter the number of rows for Triangle Pattern, Pyramid Pattern, and Downward
Triangle.
Step 3: Calculate the range.
Step 4: Print the Patterns.
Step 5: Stop.

PROGRAM :

print("Triangle Pattern")
n = int(input("Enter the number of rows"))
for i in range(0, n):
for j in range(0, i + 1):
print("* ", end="")
print()

print("Pyramid Pattern")
n = int(input("Enter the number of rows"))
for i in range(n):
for j in range(n - i - 1):
print(' ', end='')
for k in range(2 * i + 1):
print('*', end='')
print()

print("Downward Triangle")
n = int(input("Enter the number of rows"))
for i in range(n):
# internal loop run for n - i times
for j in range(n - i):
print('*', end='')
print()
OUTPUT:

Triangle Pattern
Enter the number of rows5
*
**
***
****
*****

Pyramid Pattern
Enter the number of rows5
*
***
*****
*******
*********

Downward Triangle
Enter the number of rows5
*****
****
***
**
*

RESULT:

Thus the Pyramid Pattern program are being implemented and executed successfully.
Ex.No:10 PRINT NUMBER PATTERNS
Date:

AIM:

Write a Python Program to print a number patterns.

ALGORITHM:

Step 1: Start.
Step 2: Enter the number of rows.
Step 3: Calculate the range.
Step 4: Print the number triangle and equilateral triangle pyramid with characters.
Step 5: Stop.

PROGRAM :

print("Triangle Pattern")
rows = int(input("Enter the number of rows:
")) for i in range(rows+1):
for j in range(i):
print(i, end=" ") # print number
print(" ")

print("Print equilateral triangle Pyramid with characters


") s = 5
asciiValue = 65
m = (2 * s) - 2
for i in range(0, s):
for j in range(0,
m):
print(end=" ")
m=m-1
for j in range(0, i + 1):
alphabate = chr(asciiValue)
print(alphabate, end=' ')
asciiValue += 1
print()

OUTPUT:

Triangle Pattern
Enter the number of rows: 5
1
22
333
4444
55555
Print equilateral triangle Pyramid with
characters A
B C
DEF
GHIJ
KLMNO

RESULT:

Thus the python program to print a number pattern and equilateral triangle pyramids has
been implemented and executed successfully.
Ex.No:11
Date: LIBRARY MANAGEMENT

AIM:

Write a Python Program to display, borrow and return the books from the library.

ALGORITHM:

Step 1: Start.
Step 2: Display all the books present in the
library. Step 3: Choose the books needs to be
borrowed.
Step 4: Return the books before the due date.
Step 5: Stop.

PROGRAM:

import sys
class Library:
def init (self,listofbooks):#this init method is the first method to be invoked when you
create an object
self.availablebooks=listofbooks
def displayAvailablebooks(self):
print("The books we have in our library are as
follows:")
print("================================")
for book in self.availablebooks:
print(book)
def lendBook(self,requestedBook):
if requestedBook in self.availablebooks:
print("The book you requested has now been
borrowed") self.availablebooks.remove(requestedBook)
else:
print("Sorry the book you have requested is currently not in the
library") def addBook(self,returnedBook):
self.availablebooks.append(returnedBook)
print("Thanks for returning your borrowed book")
class Student:
def requestBook(self):
print("Enter the name of the book you'd like to
borrow>>") self.book=input()
return self.book
def returnBook(self):
print("Enter the name of the book you'd like to
return>>") self.book=input()
return self.book
def main():
library=Library(["The Last Battle","The Screwtape letters","The Great Divorce"])
student=Student()
done=False
while done==False:
print(""" ======LIBRARY MENU=======
1. Display all available books
2. Request a book
3. Return a book
4. Exit
""")
choice=int(input("Enter Choice:"))
if choice==1:
library.displayAvailablebooks()
elif choice==2:
library.lendBook(student.requestBook())
elif choice==3:
library.addBook(student.returnBook())
elif choice==4:
sys.exit()
main()

OUTPUT:
Enter Choice 1
The Last Battle","The Screwtape letters","The Great Divorce
Enter Choice 2
The Last Battle book has been requested
Enter Choice 3
The book has not been returned.
Enter Choice 4
Exit.

RESULT:
Thus the library management program using python programming has been successfully
executed and verified successfully.
Ex.No:12 PRINTING COMPONENTS OF A CAR USING LIST
Date:

AIM:

Write a Python Program to print the components of a car using list.

ALGORITHM:
Step 1: Start.
Step 2: Print Blank list.
Step 3: Print the list.
Step 4: Print the list of Components in next line.
Step 5: Print the components of a car are
Step 6: Print the front components of a car are
Step 7: Stop.

PROGRAM:
List = []
print("Blank List: ")
print(List)
List = ["Engine", "Transmission","Battery","Alternator","Radiator","Front Axle","Front
Steering and Suspension","Brakes","Catalytic Converter","Muffler","Tail Pipe"] print("\
nList of Components: ")
print(List)
print("The front Components of a car are")
print(List[:8])
print(List[8:])
print(List)

OUTPUT:

Blank List:
[]
List of Components:
['Engine', 'Transmission', 'Battery', 'Alternator', 'Radiator', 'Front Axle', 'Front Steering and
Suspension', 'Brakes', 'Catalytic Converter', 'Muffler', 'Tail Pipe']
The front Components of a car are
['Engine', 'Transmission', 'Battery', 'Alternator', 'Radiator', 'Front Axle', 'Front Steering and
Suspension', 'Brakes']
['Catalytic Converter', 'Muffler', 'Tail Pipe']
['Engine', 'Transmission', 'Battery', 'Alternator', 'Radiator', 'Front Axle', 'Front Steering and
Suspension', 'Brakes', 'Catalytic Converter', 'Muffler', 'Tail Pipe']

RESULT:

Thus the program for listing the components of car using python program has been implemented
and executed successfully.
Ex.No:13 PRINT THE MATERIAL REQUIRED FOR CONSTRUCTION O
Date:

AIM:
To write a Python program to print a material required for construction of a building.

ALGORITHM:

Step 1: Start.
Step 2: Print a list.
Step 3: Print the materials required for
construction. Step 5: Print the Dictionary
Step 6: Insert the new element
Step 7: Enter the key to insert.
Step 8: Enter the value to insert.
Step 9: Enter the element to
delete. Step 10: Print the popped
key.

PROGRAM :

List=['Bamboo','Wood','Bricks','Cement Block','Crushed Bricks','Building stone',


'dry loose','Earth, dry loose','Earth, moist rammed','Gravel','Sand, dry to wet',
'Cement','Clay, dry compacted']
print('The material required for construction
are:') print(Dict)
print("Inserting a new element")
ins_key = input('Enter the key to
insert')
ins_value = input('Enter the value to insert')
Dict[ins_key] = ins_value
dele = input('Enter the element to
delete') pop_ele = Dict.pop(dele)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))

OUTPUT:
The material required for construction are:
{1: 'Bamboo', 2: 'Wood', 3: 'Bricks', 4: 'Cement Block', 5: 'Crushed Bricks', 6: 'Building stone',
7: 'dry loose', 8: 'Earth, dry loose', 9: 'Earth, moist rammed', 10: 'Gravel', 11: 'Sand, dry to
wet', 12: 'Cement', 13: 'Clay, dry compacted'}
Inserting a new element
Enter the key to insert12
Enter the value to insert12
Enter the element to
delete12
Dictionary after deletion: {1: 'Bamboo', 2: 'Wood', 3: 'Bricks', 4: 'Cement Block', 5: 'Crushed
Bricks', 6: 'Building stone', 7: 'dry loose', 8: 'Earth, dry loose', 9: 'Earth, moist rammed', 10:
'Gravel', 11: 'Sand, dry to wet', 12: 'Cement', 13: 'Clay, dry compacted'}
Value associated to poped key is: 12
RESULT:

Thus the program to print a material required for construction of a building has been
implemented and verified successfully.
Ex.No:14 SET OPERATIONS
Date:

AIM:
To write a Python program to print the some set operations.

ALGORITHM:

Step 1: Start.
Step 2: Print a Union set.
Step 3: Print the Intersection set.
Step 4: Print the Difference set.
Step 5: Print the Symmetric difference set.
Stop 6: Stop.

PROGRAM:
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};

print(“Union of E and N is”, E | N )


print(“Intersection of E and N is”, E & N )
print(“Difference of E and N is”, E – N)
print(“Symmetric difference of E and N is”, E
^N)

OUTPUT:

Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}


Intersection of E and N is {2, 4}
Difference of E and N is {0, 8, 6}
Symmetric difference of E and N is {0, 1, 2, 3, 5, 6, 8}

RESULT:

Thus the program to print a difference set operation using python program has been
implemented and verified successfully.
Ex.No:15 MATERIAL REQUIRED FOR CONSTRUCTION OF A BUILD
Date:

AIM:
To write a Python program to get a material required for construction of a building using
dictionary

ALGORITHM:
Step 1: Start.
Step 2: Print a list.
Step 3: Print the materials required for
construction. Step 5: Print the Dictionary
Step 6: Insert the new element
Step 7: Enter the key to insert.
Step 8: Enter the value to insert.
Step 9: Enter the element to
delete. Step 10: Print the popped
key.
Step 11: Stop.

PROGRAM:

Dict = {1: 'Bamboo', 2: 'Wood', 3: 'Bricks', 4: 'Cement Block', 5: 'Crushed Bricks', 6:'Building
stone',
7:'dry loose',8:'Earth, dry loose',9:'Earth, moist rammed',10:'Gravel',11:'Sand, dry to wet',
12:'Cement',13:'Clay, dry compacted' }
print('The material required for construction
are:') print(Dict)
print("Inserting a new element")
ins_key = input('Enter the key to
insert')
ins_value = input('Enter the value to insert')
Dict[ins_key] = ins_value
dele = input('Enter the element to
delete') pop_ele = Dict.pop(dele)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))

OUTPUT:
The material required for construction are:
{1: 'Bamboo', 2: 'Wood', 3: 'Bricks', 4: 'Cement Block', 5: 'Crushed Bricks', 6: 'Building stone',
7: 'dry loose', 8: 'Earth, dry loose', 9: 'Earth, moist rammed', 10: 'Gravel', 11: 'Sand, dry to
wet', 12: 'Cement', 13: 'Clay, dry compacted'}
Inserting a new element
Enter the key to insert12
Enter the value to insert12
Enter the element to
delete12
Dictionary after deletion: {1: 'Bamboo', 2: 'Wood', 3: 'Bricks', 4: 'Cement Block', 5: 'Crushed
Bricks', 6: 'Building stone', 7: 'dry loose', 8: 'Earth, dry loose', 9: 'Earth, moist rammed', 10:
'Gravel', 11: 'Sand, dry to wet', 12: 'Cement', 13: 'Clay, dry compacted'}
Value associated to poped key is: 12
RESULT:

Thus the program for the materials required for construction of a building using dictionary
has been implemented and executed successfully
Ex.No:16 PRINT FACTORIAL OF A NUMBER USING
Date: FUNCTIONS

AIM:
Write a Python program to print a factorial of a number using functions

ALGORITHM:

Step 1: Start.
Step 2: Enter a number.
Step 3: Evaluate the condition.
Step 4: Print that factorial number does not exists for negative numbers.
Step 5: Print the factorial number for positive numbers.
Step 6: Stop.

PROGRAM:

num = int(input("Enter a number: "))


factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

OUTPUT:

Enter a number: 5
The factorial of 5 is 120

Enter a number: -3
Factorial does not exist for negative numbers

RESULT:
Thus the program to print a factorial of a number has been implemented and executed
successfully.
Ex.No:17 FIND LARGEST ELEMENT IN A LIST USING
Date: FUNCTION

AIM:
Write a Python program to print a factorial of a number using functions

ALGORITHM:

Step 1: Start.
Step 2: Find the maximum no in the list.
Step 3: Evaluate the condition.
Step 4: Check the maximum value.
Step 5: Print the maximum value.
Step 6: Stop.

PROGRAM:

def max_num_in_list( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))

OUTPUT:
2

RESULT:

Thus the program to find the factorial of a number is being implemented and executed
successfully.
Ex.No:18 PRINT AREA OF SHAPES USING FUNCTIONS
Date:

AIM:
Write a python program to print the area of shapes using functions.

ALGORITHM:

Step 1: Start.
Step 2: Enter the radius of the circle.
Step 3: Calculate the radius with PI value.
Step 4: Enter the area of a rectangle with length and breadth.
Step 5: Calculate the area with Length and Breadth.
Step 6: Enter the area of a
Triangle. Step 7: Input all the 3
sides.
Step 8: Calculate with the semi perimeter.
Step 9: Calculate the Square with the area and print the area of the triangle.
Step 6: Stop.

PROGRAM:

# Area of a Circle
PI = 3.14
r = float(input(“Enter the radius of a
circle:”)) area = PI*r*r
print(“Area of a circle = %.2f” %area)

# Area of a Rectangle
L = float(input(“Enter the length of a rectangle:”))
B = float(input(“Enter the breadth of a
rectangle:”)) Area = L*B
Print(“Area of a rectangle is: %2f” %Area)

#Area of a Triangle
a = float(input(‘Enter first side:’))
b = float(input(‘Enter second side:’))
c = float(input(‘Enter third side:’))

#calculate the semi-perimeter


s = (a+b+c) /2

#calculate the square


area = (s*(s-a)*(s-b)*(s-c)**0.5
print(‘The area of the triangle is %0.2f’ %area)
OUTPUT:

Enter the radius of a circle: 32


Area of a circle = 3215.36
Enter the length of a Rectangle: 20
Enter the breath of a Rectangle: 21
Area of a Rectangle is: 420.00
Enter first side: 32
Enter Second side: 21
Enter third side: 24
The area of the triangle is 251.99
Enter first side: 32
Enter second side: 32
Area of the square = 420.0.

RESULT:

Thus the program for finding the shapes using python has been verified and executed
successfully.
Ex.No:19 PRINT REVERSE OF A STRING
Date:

AIM:

Write a Python program to print a factorial of a number using functions

ALGORITHM:

Step 1: Start.
Step 2: Define the function.
Step 3: Return the value.
Step 4: Input the string.
Step 5: Print the reverse string.
Step 6: Stop.

PROGRAM:
def my_function(x):
return x[::-1]

text = input("Enter the string which you want to reverse")


mytxt = my_function(text)

print(mytxt)

OUTPUT:

Enter the string which you want to reverse good


morning good morning
gninrom doog

RESULT:

Thus the program for reversing a string using has been implemented and executed
successfully.
Ex.No:20 CHECK FOR PALINDROME
Date:

AIM:

Write a Python program to check a given string is a palindrome or not.

ALGORITHM:

Step 1: Start.
Step 2: Input the given string.
Step 3: Check the given string with the condition
Step 4: Print the string is palindrome or not.
Step 5: Stop.

PROGRAM:

string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")

OUTPUT:

Enter a string:"Good Morning"


> "Good Morning"
'Good Morning'

Enter a string:"Good"
Not a palindrome

RESULT:

Thus the program for checking a string is a palindrome or not has been implemented and
executed successfully.
Ex.No:21 COUNT THE CHARACTER GIVEN IN THE INPUT AND TO
Date:

AIM:
To write a Python program to count the character given in the input and to replace the
characters.

ALGORITHM:

Step 1: Start.
Step 2: Input the given string.
Step 3: Check the given string with the condition
Step 4: Print the string with the replaced string.
Step 5: Stop.

PROGRAM:

string = "The best of both worlds";


count = 0;
for i in range(0, len(string)):
if(string[i] != ' '):
count = count + 1;
print("Total number of characters in a string: " + str(count));
string = string.replace("b", "B")
print(string)

OUTPUT:

Total number of characters in a string:


19 The Best of Both worlds

RESULT:

Thus the program to replace the string is being implemented and executed successfully.
Ex.No:22 CREATE AN ARRAY AND PERFORM BASIC ARRAY OPERA
Date:

AIM:

To write a Python program to create an array and perform a basic array operations
using a numpy.

ALGORITHM:

Step 1: Start.
Step 2: Create an array object.
Step 3: Check the given array with the condition
Step 4: Print the dimension, shape and size of an
array. Step 5: Stop.

PROGRAM:

import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)
# Printing shape of array
print("Shape of array: ", arr.shape)
# Printing size (total number of elements) of
array print("Size of array: ", arr.size)
# Printing type of elements in array
print("Array stores elements of type: ", arr.dtype)

OUTPUT:

Array is of type: <class 'numpy.ndarray'>


No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64

RESULT:

Thus the program to create an array and perform a basic array operations has been
implemented and executed successfully.
Ex.No:23 READING CSV FILES
Date:

AIM:
Write a Python program to read a CSV files.

ALGORITHM:

Step 1: Start.
Step 2: Create an array object with csv file.
Step 3: Open the csv file with write mode.
Step 4: Delimit the csv file using a single quotation.
Step 5: Print the output
Step 6: Stop.

PROGRAM:
import csv

# creating a nested list of roll numbers,


# subjects and marks scored by each roll
number marks = [
["RollNo", "Maths", "Python"],
[1000, 80, 85],
[2000, 85, 89],
[3000, 82, 90],
[4000, 83, 98],
[5000, 82, 90]
]

# using the open method with 'w' mode


# for creating a new csv file 'my_csv' with .csv extension
with open('my_csv.csv', 'w', newline = '') as file:
writer = csv.writer(file, quoting = csv.QUOTE_NONNUMERIC,
delimiter = ' ')
writer.writerows(marks)

# opening the 'my_csv' file to read its contents


with open('my_csv.csv', newline = '') as file:

reader = csv.reader(file, quoting = csv.QUOTE_NONNUMERIC,


delimiter = ' ')

# storing all the rows in an output list


output = []
for row in reader:
output.append(row[:])

for rows in output:


print(rows)

OUTPUT:

["RollNo", "Maths", "Python"],


[1000.0, 80.0, 85.0],
[2000.0, 85.0, 89.0],
[3000.0, 82.0, 90.0],
[4000.0, 83.0, 98.0],
[5000.0, 82.0, 90.0]

RESULT:

Thus the Python Program to read CSV files has been verified and successfully executed.
Ex.No:24 SORTING OF TUPLES
Date:

AIM:
To write a Python program to sort a list of tuples

ALGORITHM:

Step 1: Start.
Step 2: Create a tuples for sorting.
Step 3: Check with the condition given.
Step 4: Print the output
Step 5: Stop.

PROGRAM:
def SortTuple(tup):

# Getting the length of list


# of tuples
n = len(tup)

for i in range(n):
for j in range(n-i-1):

if tup[j][0] > tup[j + 1][0]:


tup[j], tup[j + 1] = tup[j + 1], tup[j]

return tup

# Driver's code

tup = [("Amana", 28), ("Zenat", 30), ("Abhishek", 29),


("Nikhil", 21), ("B", "C")]

print(SortTuple(tup))

OUTPUT:

[('Abhishek', 29), ('Amana', 28), ('B', 'C'), ('Nikhil', 21), ('Zenat', 30)]

RESULT:

Thus the python program to sort a list of tuples alphabetically has been executed and verified
successfully.
Ex.No:25 ADDING AND SUBTRACTING OF ELEMENTS IN A
Date: MATRIX

AIM:
Write a Python program to add and subtract of matrix elements.

ALGORITHM:
Step 1: Start.
Step 2: Create a Matrix for addition and subtraction.
Step 3: Checks the matrix values based on array Object given.
Step 4: Print the output for both addition and subtraction.
Step 5: Stop.

PROGRAM:

import numpy as np

# creating first matrix


A = np.array([[1, 2], [3, 4]])

# creating second matrix


B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)

# adding two matrix


print("Addition of two matrix")
print(np.add(A, B))

#Subtraction
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])

# creating second matrix


B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# subtracting two matrix
print("Subtraction of two matrix")
print(np.subtract(A, B))
OUTPUT:
Printing elements of first matrix
[[1 2]
[3 4]]
Printing elements of second matrix
[[4 5]
[6 7]]
Addition of two matrix
[[5 7]
[9 11]]

Printing elements of first matrix


[[1 2]
[3 4]]
Printing elements of second matrix
[[4 5]
[6 7]]
Subtraction of two matrix
[[-3 -3]
[-3 -3]]

RESULT:

Thus the program using Python to calculate and addition and subtraction of two matrix has
been executed and verified successfully.
Ex.No:26 COPYING THE CONTENT OF A FILE AND COUNTING
Date: THEM

AIM:

To write a Python program to copy the content of a file and counting the no of words
present in it.

ALGORITHM:

Step 1: Start.
Step 2: Create a text file and write some word.
Step 3: Check the text file with the given
condition Step 4: Print the output.
Step 5: Stop.

PROGRAM:

# Opening a file
file = open("gfg.txt","r")
Counter = 0

# Reading from file


Content = file.read()
CoList = Content.split("\n")

for i in CoList:
if i:
Counter += 1

print("This is the number of lines in the file")


print(Counter)

OUTPUT:

This is the number of lines in the file


4

RESULT:

Thus the Python program for counting the no of lines in a file has been executed and
successfully verified.
Ex.No:27 DIVIDE BY ZERO USING EXCEPTION HANDLING
Date:

AIM:

Write a Python program to divide by zero using exception handling

ALGORITHM:

Step 1: Start.
Step 2: Input the Value of n, d, c.
Step 3: Check the given values with the condition
Step 4: Print the result.
Step 5: Stop.

PROGRAM:

n=int(input("Enter the value of


n:")) d=int(input("Enter the value
of d:")) c=int(input("Enter the value
of c:")) try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")

OUTPUT:

Enter the value of n: 25


Enter the value of d: 3
Enter the value of c: 10
Quotient: -3.5714285714285716

Enter the value of n: 30


Enter the value of d: 0
Enter the value of c: 0
Division by Zero!

RESULT:

Thus the program to divide by zero using exception handling has been implemented and
executed successfully.
Ex.No:28 VOTERS AGE USING EXCEPTION HANDLING
Date:

AIM:
Write a Python program to find the voters age using Exception Handling

ALGORITHM:
Step 1: Start.
Step 2: Input the age.
Step 3: Check the given values with the condition
Step 4: Print the result.
Step 5: Stop.

PROGRAM:
# input age
age = int(input(“Enter Age:”))

#condition to check voting eligibility


if age>=18:
status=”Eligible”
else:
status=”Not Eligible”
print(“You are”, status,” for Vote.”)

OUTPUT:

Enter Age: 35
You are Eligible for Vote.

RESULT:

Thus the program for finding the voters age using python is executed and verified successfully.
Ex.No:29 STUDENTS MARK RANGE VALIDATION USING EXCEPTIO
Date:

AIM:
Write a Python program to validate a student mark range using exception handling

ALGORITHM:

Step 1: Start.
Step 2: Input the coursework mark.
Step 3: Check the given values with the condition
Step 4: Print the result.
Step 5: Stop.

PROGRAM:

try:
while True:
coursework = int(input("Enter the Coursework Mark: "))
if coursework < 0 or coursework > 100:
print("The value is out of range, try
again.") else:
break

except ZeroDivisionError:
print("Can't divide by zero")
except NameError:
print("Name error has occured")
finally:
print('This is always executed')

OUTPUT:

Enter the Coursework Mark: -1


The value is out of range, try
again. Enter the Coursework
Mark: 2 This is always executed

RESULT:

Thus the program for coursework mark has been implemented and executed successfully.

You might also like