0 ratings 0% found this document useful (0 votes) 2 views 16 pages Python Lab Programs
The document outlines a series of Python programming exercises covering various topics such as data types, arithmetic operations, string manipulations, date handling, list and tuple operations, dictionaries, control flow statements, and mathematical functions. It includes specific programming tasks like calculating the factorial of a number, handling user-defined exceptions, and creating modules for Fibonacci numbers. Additionally, it provides examples and outputs for each program to demonstrate their functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Python Lab Programs For Later _= PRESIDENCY COLLEGE
1. Write a program to demonstrate different number datatypes in
python.
. Write a program to perform different arithmetic operations on
numbers in python
. Write a program to perform different string operations.
- Write a python script to print the current date
- Write a python program to perform list operations in python.
Write a program to demonstrate working with tuples in python
Write a program to demonstrate working with dictionaries in
python
8. Write a program to demonstrate working of if..else if in Python
Write a program to demonstrate working of Switch statement
9. Write a program to calculate sum of series
10. Write a python program to find factorial of a number using
recursio
Part B:
11. Write a python program to define a module to find Fibonacci
Numbers and import the module to another program
12. Write a script named copyfile.py. This script should prompt
‘the user for the
names of two text files. The contents of the first the second
file should be same.
13. Write a program to compute area of following shape:
rectangle and triangle
14, Write a program to reverse the given number
15. Write Python program to demonstrate math built- in functions
16. Write a program in Python to handle user defined exception for
given problem
17. Write a program using a while loop that asks the user for a
number,
and prints a countdown from that number to zero.
18. Write a program to find mean, median, mode for the given set
of numbers in a list.
19. Write a program find even sum and odd sum for given range of
numbers
20. Write a program to check if the given string is palindrome or
not
woo a
: circle,
BY: DR NANDAKUMAR,DR VASANTHA Page 1= PRESIDENCY COLLEGE
a.
# Python program to demonstrate the numeric values.
a=5
print(" Value of a is: ", a)
print("Type of a: ", type(a))
b=5.0
print(" Value of b is: ", b)
print("\nType of b: ", type(b))
e=24+43
print(" Value of ¢ is: ", c)
print("\nType of ¢: ", type(c))
Program 2
# Python program to perform arithmetic operations.
# Receiving the input
numl = input('Enter first number: ')
num2 = input('Enter second number: ')
# Arithmetic operations
sum = float(numl) + float (num2)
float(numl) - float (num2)
float (numl) * float (num2)
float(numl) / float (num2)
mul,
div
# Printing the results
print('The sum of {0} and {1} is (2}'.format(num1, num2, sum))
print('The subtraction of {0} and {1} is {2}'.format(numl, num2,
min))
print('The multiplication of {0} and {1} is {2}'.format(numl, num2,
mul))
print('The division of {0} and {1) is (2}'.format(numl, num2, div))
Program 3
# Python program to demonstrate string operations
stri="Welcome you all students"
capital=stri. upper ()
print (capital)
BY: DR NANDAKUMAR,DR VASANTHA Page 2= PRESIDENCY COLLEGE
a.
small=capital. lower ()
print (small)
str2qstri. replace ("'students", "engineers")
print (str2)
st=" This is an example of strip "
left=st.1strip()
print (left)
right=st.rstrip()
print (right)
prefixl=str1.startswith ("Welcome")
print (prefixl)
prefix2=str2.startswith("s")
print (prefix2)
prefix3=str2.endswith("w"
print (prefix3)
#Python program to print the current date.
from datetime import date
today = date. today()
# dd/mm/yy
dl = today. strftime ("$d/%m/S¥")
print("dl =", 41)
# Textual month, day and year
d2 = today. strftime("$B td, %¥")
print("d2 =", 2)
# mm/dd/y
43 = today. strftime("%m/4d/sy")
print("d3 =", 43)
# Month abbreviation, day and year
44 = today. strftime("%b-3d-3¥")
print ("d4 =", d4)
BY: DR NANDAKUMAR,DR VASANTHA Page 3= PRESIDENCY COLLEGE
=_—
5. Write a python program to perform list operations.
# Creating a List
List = [1,2,3]
print("Initial List: ")
print (List)
List. append (2)
List. append (4)
print("\n List after Addition of Three elements: ")
print (List)
# Addition of Element at specific Position using Insert Method
List. insert (3,12)
List. insert (4,14)
print("\n List after performing Insert Operation
print (List)
# Removing elements from List using remove() method
List. remove (1)
List. remove (2)
print("\n List after Removal of two elements:
print (List)
# Print elements of a range using Slice operation
Sliced_List = List[2:4]
print("\nSlicing elements in a range 2-4: ")
print (Sliced_List)
# Addition of List to a List using append () method
List2 = [8,10]
List. append (List2)
print("\n List after Addition of a List: ")
print (List)
output:
Initial List:
[1, 2, 31
List after Addition of Three elements:
(1, 2, 3, 2, 4]
List after performing Insert Operation:
[1, 2, 3, 12, 14, 2, 4]
List after Removal of two elements:
BY: DR NANDAKUMAR,DR VASANTHA Page 4= PRESIDENCY COLLEGE
=_—
[3, 12, 14, 2, 4]
Slicing elements in a range 2-:
(14, 21
List after Addition of a List:
[3, 12, 14, 2, 4, [8, 101)
# Creating an empty Tuple
Tuplel = ()
print ("Initial empty Tuple: ")
print (Tuplel)
# Creating a Tuple with the use of string
Tuple2 = ('Chennai', 'Delhi')
print("\nTuple with the use of String: ")
print (Tuple2)
# Creating a Tuple with the use of list
listl = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print (tuple (1ist1))
# Creating a Tuple with the use of built-in function
Tuple3 = tuple('Bengaluru')
print("\nTuple with the use of function: ")
print (Tuple3)
# Printing the values of Tuple
print("\nFirst element of Tuple: ")
print (Tuple3[0])
# Tuple unpacking. This line unpack values of Tuple2
a, b = Tuple2
print("\nValues after unpacking: ")
print (a)
print (b)
output:
Initial empty Tuple:
0
Tuple with the use of String:
(‘Chennai', 'Delhi')
Tuple using List:
(1, 2, 4, 5, 6)
BY: DR NANDAKUMAR,DR VASANTHA Page S= PRESIDENCY COLLEGE
a.
Tuple with the use of function:
(BY, tet, tnt, 'g',
First element of Tuple:
B
Values after unpacking:
Chennai
Delhi
fat, tL, ta,
# demo for all dictionary methods
dict1 = (1: "Python", 2:
Java", 3: "Ruby", 4: "Scala"}
# copy() method
dict2 = dicti.copy()
print (dict2)
# clear() method
dict1.clear()
print (dict1)
# get() method
print (dict2.get(1))
# items() method
print (dict2.items())
# keys() method
print (dict2.keys())
# pop() method
dict2.pop (2)
print (dict2)
# popitem() method
dict2.popitem()
print (dict2)
# update () method
dict2.update ({3
print (dict2)
# values () method
cala"})
print (dict2.values())
BY: DR NANDAKUMAR,DR VASANTHA Page 6TAUTONOMO
_== PRESIDENCY COLLEGE
output:
{1: ‘Python’, 2: ‘Java’, 3: 'Ruby', 4: 'Sca!
{}
Python
dict_items([(1, 'Python'), (2, ‘Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 41)
{1: ‘Python’, 3: 'Ruby', 4
{1: ‘Python’, 3: 'Ruby'}
{1: 'Python', 3: 'Scala'}
dict_values(['Python', 'Scala'])
*Scala'}
# Program 8. Demonstrating the if statements
name = input ("Enter your Name:")
regne = input ("Enter your Reg.No. :")
marks = int (input ("Enter your Average Mark: "))
Se irrercerececerer te esececseetccctetecrrs soc recercrcccesecny)
print ("Result
if marks >= 4
if marks > 75 and marks <= 100:
print ("Congrats ! you passed in First class with Distinction
+ regno, name)
set)
elif marks >= 60 and marks <- 7
print ("Congrats ! you passed in First class .
elif marks >= 50 and marks < 60:
print ("You passed in Second class
else:
print ("You passed in Third class
else:
print ("Sorry, you failed")
BELEN (Hon ENGR ENE RENEE NEEDS SI IIIB ONIN I RENIN DIDIDIDIN)
Enter your Name:Vijay
Enter your Reg.No. :21B013
Enter your Average Mark: 78
BY: DR NANDAKUMAR,DR VASANTHA Page 7= PRESIDENCY COLLEGE
a.
Result: 218013 Vijay
Congrats ! you passed in First class with Distinction ...
# Program 9, Write a program to calculate sum of series
n=int (input ("Enter the value of 'n' = "))
sum = 0
for i in range(1,n+1):
Sum of the series is", sum)
Enter the value
Sum of the series is 55
Program 10: Program to find factorial of given number
def factorial (n):
# Checking the number is 1 or 0 then return 1 other wise return
factorial
if (n= lorn
return 1
else:
return (n * factorial(n - 1))
num = int (input ("Enter a number: "))
print ("number : ", num)
print ("Factorial : ", factorial (num))
output:
Enter a number: 5
number: 5
Factorial : 120
# Part 1: Defining a module (ex. fib.py)
def fibo(n): — # write Fibonacci series up to n
BY: DR NANDAKUMAR,DR VASANTHA Page 8= PRESIDENCY COLLEGE
a.
while b <= n:
print (b, end=' ')
a, b=b, atb
print ()
def fibo2(n): # return Fibonacci series up to n
result = []
a,b=0,1
while b <= n:
result. append (b)
a, b=b, atb
return result
# Part 2: Importing the module to print the Fibonacci series (ex.
£b-py)
import fib
n = int(input ("Enter the number to generate the Fibonacci
series:"))
print (£ib. £ibo(n))
output:
Enter the number to generate the Fibonacci series:55
11235813 21 34 55
None
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
fileHandle = open(sFile, "r"
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile
for s in texts:
fileHandle.write(s)
fileHandle.close()
BY: DR NANDAKUMAR,DR VASANTHA Page 9= PRESIDENCY COLLEGE
a.
print ("\nFile Copied Successfully!")
output:
Note: Before executing this program create a file (source file)
filel.txt with some content. If the target file does not exist, it
will be created automatically during the execution.
Enter the Name of Source File:filel.txt
Enter the Name of Target File: file2.txt
File Copied Successfully!
print ( "l-rectangle, 2-triangle, 3-circle" )
figure = input ( "Select a shape:" )
if figure == '1' :
print ( "The lengths of the sides of the rectangle:" )
a = float (input ("a =" ))
b = float (input ( "b=" ))
print ( "Area:% .2£" % (a * b))
elif figure == '2' :
print ( "The lengths of the sides of the triangle:" )
a = float (input ( "a =" ))
float (input ( "b =" ))
¢ = float (input ( )
p=(a+btc) /2
from math import sqrt
8 = sqrt (p * (p - a) * (p- b) * (P - c))
print ( "Area: .2£" & s)
elif figure == '3'
x = float (input ( "Circle radius R =" ))
from math import pi
print ( "Area:$ .2£" % (pi * x ** 2 ))
else
print ( "Input error" )
output:
1-Rectangle, 2-Triangle, 3-Circle
Select a shapt
The lengths of the sides of the rectangle:
a=3
BY: DR NANDAKUMAR,DR VASANTHA Page 10NCY COLLEGE
ToS}
Area: 12.00
1-Rectangle, 2-Triangle, 3-Circle
Select a shape:2
The lengths of the sides of the triangle:
a =3
b=5
© =6
Area: 7.48
1-Rectangle, 2-Triangle, 3-Circle
Select a shapt
Circle radius R =5
Area: 78.54
Program 14: Write a program to reverse the given number
Number = int (input("Please Enter any Number: "))
Reverse = 0
while (Number > 0):
Reminder = Number % 10
Reverse = (Reverse * 10) + Reminder
Number = Number // 10
print("\n Reverse of entered number is = td" % Reverse)
output:
Please Enter any Number: 123
Reverse of entered number is = 321
import math
sq = math.sart (64)
ce = math.ceil(1.
£1 = math. floor (1
p = math.pi
po = pow(4, 3)
mi = min(5, 10, 25)
ma = max(5, 10, 25)
ab = abs (-7.25)
anglDegree = 90
anglRadian = math. radians (anglDegree)
BY: DR NANDAKUMAR,DR VASANTHA Page 11== PRESIDENCY COLLEGE
=_
int ("sqrt (64) is:', sa)
print (‘ceil(1.4) is:", ce)
‘floor (1.4) , ti)
print ("pi(1.4) is:', p)
print ("pow(4,3) is:", po)
nt ("min (5,10,25) iss", mi)
print ("max (5,10,25) is:', ma)
print ("abs (-7.25) ab)
t ("The given angle is :', anglRadian)
‘sin(x) is
e('cos(x) is
int ("tan (x) is
math.sin(anglRadian))
) math. cos (anglRadian))
» math. tan (anglRadian))
output:
sqrt (64) is: 8.0
i1(1.4)
floor (1.4)
pi(l.4) is: 3.
pow (4,3) is: 64
min(5,10,25) is:
1592653589793
5
max(5,10,25) is: 25
abs (-7.25) is: 7.25
The given angle is : 1.5707963267948966
sin (x) 1.0
s(x) is : 6,123233995736766e-17
tan(x) is : 1.633123935319537e+16
Program 16: User defined exception
class FiveDivisionError (Exception) :
#this is exception class called when five division error
happens
pass
nt (input ("Enter first number:"))
nt (input ("Enter second number:"))
BY: DR NANDAKUMAR,DR VASANTHA Page 12NCY COLLEGE
ToS}
raise FiveDivisionError ("cannot divide by five")
diveni/n2
print ("division is:",div)
except (FiveDivisionError,ZeroDivisionError) as var:
print (var)
Outputi:
Enter first number:4
Enter second number:5
cannot divide by five
output2:
Enter first number: 4
Enter second nunber:3
division is: 1.3333333333333333
# Program 17. Write a program using a while loop that asks the user
for a number, and prints a countdown from that number to zero.
n= int (input ("Enter A Number--->"));
while n >
print (n);
nen-l;
Enter A Number--->8
collecti
list (map (int, input ("Enter the numbers:
n= len (num)
ns import Counter
split()))
BY: DR NANDAKUMAR,DR VASANTHA Page 13PRESIDENCY COLLEGE
TAUTONOMO
# Calculation of Mean
sum = sum (num)
mean = sum / n
print ("Mean is: ", mean)
# Calculation of Median
num. sort ()
ifn 2-=0:
medianl = num[n//2)
median2 = num{n//2 - 1)
median = (medianl + median2) /2
else:
median = num(n//2]
print ("Median is: ", median)
# Calculation of Mode
data = Counter (num)
get_mode = dict (data)
mode - [k for k, v in get_mode.items() if v
max (List (data.values()))]
# {key:value for key, value in iterable if condition}
if len (mode)
get_mode
else:
get_mode =
'No mode found"
Mode is/are: "+ ', '.join(map(str, mode))
print (get_mode)
output:
Enter the numbers:2 22345678
Mean is: 4,333333333333333
Median is: 4
Mode is/are: 2
BY: DR NANDAKUMAR,DR VASANTHA Page 14TAUTONOMO
_== PRESIDENCY COLLEGE
# Program 19. Write a program find even sum and odd sum for given
range of numbers
maximum = int (input (" Please Enter the Maximum Value : ")}
even_total = 0
odd_total = 0
for number in range (1, maximum + 1):
if (number % 2 == 0):
even_total = even_total + number
else:
odd_total = odd_total + number
print ("The Sum of Even Numbers from 1 to (0) = {1)".format (number,
even_total))
print ("The Sum of Odd Numbers from 1 to (0) = (1)". format (number,
odd_total))
Please Enter the Maximum Value : 10
The Sum of Even Numbers from 1 to 10 = 30
The Sum of Odd Numbers from 1 to 10 = 25
# Program 20. Write a program to check if the given string is
palindrome or not
fusing built-in function
word = input ("Enter any wor
rev = reversed (word)
if list (word) ==List (rev):
print ("It is a palindrome')
else:
print ("It is not a palindrome')
"
#Palindrome program in python without usin
string=input ("Enter any word:")
if(stringssstring[::-1]):
print ("It is a palindrome")
n function
els.
print (‘It is not a palindrome")
BY: DR NANDAKUMAR,DR VASANTHA Page 15= PRESIDENCY COLLEGE
(ne
Enter any word: madam
It is a palindrome
Enter any word: hello
It is not a palindrome
TRS OSHS EHD HOnODeHOEIALL THE BESTTOCH HG HEneHnunnonioe
BY: DR NANDAKUMAR,DR VASANTHA Page 16