Python Programming Lab(21AML38)
‘ ‘ ‘1 a. Develop a program to read the students details like Name, USN, and Marks in three subjects.
Display the student’s details, total marks and percentage with suitable messages.’ ‘ ‘
name=str(input("enter the name of the student: "))
usn=str(input("enter the usn of the student: "))
m1=int(input("enter the marks of subject 1: "))
m2=int(input("enter the marks of subject 2: "))
m3=int(input("enter the marks of subject 3: "))
#m4=int(input("enter the marks of subject 4:"))
#m5=int(input("enter the marks of subject 5:"))
total=m1+m2+m3
per=total/3
print("total:",total)
print("percentage:",per)
if(per>=60):
print("first division")
elif(per>=50 and per<=59):
print("second division:")
elif(per>=40 and per<=49):
print("third division:")
else:
print("fail...")
1
Python Programming Lab(21AML38)
OUTPUT
== case – 1==
enter the name of the student: AMBIKA
enter the usn of the student: SW20AIM001
enter the marks of subject 1: 88
enter the marks of subject 2: 99
enter the marks of subject 3: 78
total: 265
percentage: 88.33333333333333
first division
==case -2==
enter the name of the student: GANGA
enter the usn of the student: SW20AIM007
enter the marks of subject 1: 55
enter the marks of subject 2: 45
enter the marks of subject 3: 45
total: 145
percentage: 48.333333333333336
third division:
2
Python Programming Lab(21AML38)
1b. Develop a program to read the name and year of birth of a person. Display whether the person is a
senior citizen or not
name=str(input("enter the name of the person:"))
birth_year=int(input("Enter Year of Birth:"))
current_year=int(input("Enter Current Year :"))
age=current_year-birth_year
if (age>60):
print("Senior")
else:
print("Not Senior")
OUTPUT
enter the name of the person:AMBIKA
Enter Year of Birth:2003
Enter Current Year :2023
Not Senior
enter the name of the person:GANGA
Enter Year of Birth:1947
Enter Current Year :2023
Senior
3
Python Programming Lab(21AML38)
1c . Implementing program using Strings. (Reverse, palindrome, character count, replacing characters)
''' REVERSE A STRING '''
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:]) + text[:1]
print(reversed_string("Python Programming!"))
''' PALINDROME '''
def isPalindrome(s):
return s == s[::-1]
s = input("enter any string :")
ans = isPalindrome(s)
if ans:
print(s,"Yes it's a palindrome")
else:
print(s,"No it's not a palindrome")
'''CHARACTER COUNT'''
def count_chars(txt):
result = 0
for char in txt:
result += 1 # same as result = result + 1
return result
text=input("enter any string")
print("no.of characters in a string",count_chars(text))
'''REPLACING CHARACTERS'''
string = "python programming language is powerful"
print(string.replace("p", "P",1))
print(string.replace("p", "P"))
4
Python Programming Lab(21AML38)
OUTPUT
!gnimmargorP nohtyP
enter any string :MADAM
MADAM Yes it's a palindrome
enter any string :MAA
MAA No it's not a palindrome
enter any string MANGO
no.of characters in a string 6
Python programming language is powerful
Python Programming language is Powerful
5
Python Programming Lab(21AML38)
2a. Write a program to demonstrate different number data types in python and perform different
Arithmetic operations on numbers in python.
a=10
b=8.5
c=2.05j
print("a is type of",type(a))
print("b is type of",type(b))
print("c is type of",type(c))
num1=int(input("enter first number:"))
num2=int(input("enter second number:"))
print("addition of num1 and num2:",num1+num2)
print("subtraction of num1 and num2:",num1-num2)
print("multiplication of num1 and num2:",num1*num2)
print("division of num1 and num2:",num1/num2)
print("remainder of num1 and num2:",num1%num2)
print("exponent of num1 and num2:",num1**num2)
print("floored division of num1 and num2:",num1//num2)
OUTPUT
a is type of <class 'int'>
b is type of <class 'float'>
c is type of <class 'complex'>
enter first number:6
enter second number:7
addition of num1 and num2: 13
subtraction of num1 and num2: -1
multiplication of num1 and num2: 42
division of num1 and num2: 0.8571428571428571
remainder of num1 and num2: 6
exponent of num1 and num2: 279936floored division of num1 and num2: 0
6
Python Programming Lab(21AML38)
2b. Write a program to create, concatenate and print a string and accessing sub-string
from a given string.'''
s1=input("Enter first String : ")
s2=input("Enter second String : ")
print("First string is : ",s1)
print("Second string is : ",s2)
print("concatenations of two strings :",s1+s2)
print("Substring of given string :",s1[1:4])
OUTPUT
Enter first String : MADAM
Enter second String : MAM
First string is : MADAM
Second string is : MAM
concatenations of two strings : MADAMMAM
Substring of given string : ADA
7
Python Programming Lab(21AML38)
2c. Write a python script to print the current date in the following format Sun May 29
02:26:23 IST 2017
import time;
ltime=time.localtime();
print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime)); #returns the formatted time
'''
%a : Abbreviated weekday name.
%b : Abbreviated month name.
%d : Day of the month as a decimal number [01,31].
%H : Hour (24-hour clock) as a decimal number [00,23].
%M : Minute as a decimal number [00,59].
%S : Second as a decimal number [00,61].
%Z : Time zone name (no characters if no time zone exists).
%Y : Year with century as a decimal number.'''
OUTPUT
====== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python311/tm.py ======
Tue Mar 28 16:30:08 India Standard Time 2023
8
Python Programming Lab(21AML38)
3a. ''' Write a python program to find largest of three numbers '''
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
OUTPUT
====== RESTART: C:/Users/HP/AppData/Local/Programs/Python/Python311/P3B.PY =====
Enter first number: 8
Enter second number: 9
Enter third number: 7
The largest number is 9
9
Python Programming Lab(21AML38)
3b. Develop a program to generate Fibonacci Sequence of length(N). Read N from the console
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
10
Python Programming Lab(21AML38)
OUTPUT
How many terms? 4
Fibonacci sequence:
11
Python Programming Lab(21AML38)
3c. Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R)
print("enter a number:",end='')
try:
num=int(input())
fact=1
for i in range(1,num+1):
fact=fact*i
print("\n factorial of",num,"=",fact)
except ValueError:
print("\n invalid input!")
def binomialCoeff(n, k):
if k > n:
return 0
if k == 0 or k == n:
return 1
# Recursive Call
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)
12
Python Programming Lab(21AML38)
OUTPUT
enter a number:4
factorial of 4 = 1
factorial of 4 = 2
factorial of 4 = 6
factorial of 4 = 24
13
Python Programming Lab(21AML38)
4 a. Implementing program using Functions (Largest number in a list, area of shape)
#Largest number in a list
def mymax(list1):
max=list1[0]
for x in list1:
if x>max:
max=x
return max
list1=[10,20,30,40,55,99]
print("largest element is:",mymax(list1))
#Area of shape
def calculate_area(name):
if name=="rectangle":
l=int(input("enter rectangle length:"))
b=int(input("enter rectangle breadth:"))
rect_area=l*b
print(f"the area of rectangle is {rect_area}")
elif name=="square":
s=int(input("enter square side length:"))
sqt_area=s*s
print(f"the area of square is {sqt_area}")
elif name=="triangle":
h=int(input("enter triangle height length:"))
b=int(input("enter triangle breadth length:"))
tri_area=0.5*h*b
print(f"the area of triangle is {tri_area}")
elif name=="circle":
r=int(input("enter circle radius length:"))
pi=3.14
circ_area=pi*r*r
print(f"the area of circle is {circ_area}")
elif name=="parallelogram":
14
Python Programming Lab(21AML38)
b=int(input("enter parallelogram base length:"))
h=int(input("enter parallelogram height length:"))
para_area=b*h
print(f"the area of parallelogram is {para_area}")
else:
print("sorry! this shape is not available.")
if __name__=="__main__":
print("calculate shape area")
shape_name=input("enter the name of shape whose area you want to find:")
calculate_area(shape_name)
OUTPUT
calculate shape area
enter the name of shape whose area you want to find:triangle
enter triangle height length:5
enter triangle breadth length:3
the area of triangle is 7.5
15
Python Programming Lab(21AML38)
4b. implementing a real-time/technical application using Exception handling (Divide by Zero error,
Voter’s age validity, student mark range validation)
# divide by Zero error
a=int(input("enter a:"))
b=int(input("enter b:"))
try:
c=((a+b)/(a-b))
if a==b:
raise ZeroDivisionError
except ZeroDivisionError:
print("a/b result is 0")
else:
print(c)
#2.Voter's Age Validity
print("Voter's Age Validity")
def voting():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
voting()
# student mark range validation
name=input("enter the student name:")
regno=input("enter the student register number:")
16
Python Programming Lab(21AML38)
try:
mark1=int(input("enter the mark1:"))
mark2=int(input("enter the mark2:"))
if(0<=mark1<=100)and(0<=mark2<=100):
print("marks are in the range")
else:
raise ValueError("marks are not in range")
except ValueError as err:
print(err)
finally:
print("thankyou,you have successfully checked")
OUTPUT
enter a:5
enter b:5
a/b result is 0
Voter's Age Validity
Enter your age32
Eligible to vote
enter the student name:jerry
enter the student register number:sw21aim001
enter the mark1:70
enter the mark2:30
marks are in the range
thankyou,you have successfully checked
17
Python Programming Lab(21AML38)
5 a. “LIST1” is a list that contain “N” different SRN of students read using a user-defined function with
the help of input () function.it is required to add the SRN of “M” for more students that are to be
appended or inserted into “LIST1” at the appropriate place. The program must return the index of the
SRN entered by the user.
list1=['SW21AIM001','SW21AIM002','SW21AIM004','SW21AIM005']
print("list is:",list1)
list1.append("SW21AIM003")
print("list is:",list1)
list1.remove("SW21AIM002")
print("updated list is:",list1)
OUTPUT
list is: ['SW21AIM001', 'SW21AIM002', 'SW21AIM004', 'SW21AIM005']
list is: ['SW21AIM001', 'SW21AIM002', 'SW21AIM004', 'SW21AIM005', 'SW21AIM003']
updated list is: ['SW21AIM001', 'SW21AIM004', 'SW21AIM005', 'SW21AIM003']
18
Python Programming Lab(21AML38)
5b.TUPLE1” and “TUPLE2” are two tuples that contain “N” values of different data types read using
the user -defined function “READ” with the help of the input () function. Elements of “TUPLE1” and
“TUPLE2” are to be read one at a time and the “larger” value among them should be placed into
“TUPLE3”. Display all tuples.
tuple1=('0','1','2','student')
tuple2=('python','geek')
print(tuple1+tuple2)
print("max value elemant:",max(tuple1))
print("max value elemant:",max(tuple2))
tuple3=(max(tuple1),max(tuple2))
print(tuple3)
OUTPUT
('0', '1', '2', 'student', 'python', 'geek')
max value elemant: student
max value elemant: python
('student', 'python')
19
Python Programming Lab(21AML38)
6a. SET1 and SET2 are two sets that contain unique integers. SET3 is to be created by taking the
union or intersection of SET1 and SET2 using the user defined function Operation (). Perform either
union or intersection by reading the choice from the user. Do not use built-in function union () and
intersection () and also the operators “|” and “&”.
set1=[1,2,3,4,5,6]
set2=[1,2,3,5,7,9,10]
set3=[]
def operation(choice):
if choice=="union":
for row in set2:
set1.append(row)
for col in set1:
set3.append(col)
elif choice=="intersection":
for row in set1:
if row in set2:
set3.append(row)
for col in set2:
if col in set1:
set3.append(col)
return set(set3)
print(operation("intersection"))
OUTPUT
#intersection
{1, 2, 3, 5}
#union
{1, 2, 3, 4, 5, 6, 7, 9, 10}
20
Python Programming Lab(21AML38)
6b. The Dictionary “DICT1” contains N Elements and each element in the dictionary has the operator
as the KEY and operands as VALUES. Perform the operations on operands using operators stored as
keys. Display the results of all operations.
dict1={'stdno':'532','stuname':'naveen','stuage':'21','stucity':'hyderabad'}
print("\n dictionary is:",dict1)
print("\n student name is:",dict1['stuname'])
print("\n student city is:",dict1['stucity'])
print("\n all key in dictionary")
for x in dict1:
print(x)
print("\n all key in dictionary")
for x in dict1:
print(dict1[x])
dict1["phno"]=6884762859
print("updated dictionary is:",dict1)
dict1["stuname"]="jerry"
print("updated dictionary is:",dict1)
dict1.pop("stuage")
print("updated dictionary is:",dict1)
print("length of dictionary is:",len(dict1))
dict2=dict1.copy()
print("\n new dictionary is:",dict2)
dict1.clear()
print("updated dictionary is:",dict1)
21
Python Programming Lab(21AML38)
OUTPUT
dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad'}
student name is: naveen
student city is: hyderabad
all key in dictionary
stdno
stuname
stuage
stucity
all key in dictionary
532
naveen
21
hyderabad
updated dictionary is: {'stdno': '532', 'stuname': 'naveen', 'stuage': '21', 'stucity': 'hyderabad', 'phno':
6884762859}
updated dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stuage': '21', 'stucity': 'hyderabad', 'phno':
6884762859}
updated dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859}
length of dictionary is: 4
new dictionary is: {'stdno': '532', 'stuname': 'jerry', 'stucity': 'hyderabad', 'phno': 6884762859}
updated dictionary is: {}
22
Python Programming Lab(21AML38)
7a Read N numbers from the console and create a list. To find mean, variance and standard deviation
of given numbers
import statistics
a = list()
number = int(input( "Enter the number of elements you want: "))
print ('Enter numbers in array: ')
for i in range(int(number)):
n = input( "number : ")
a.append ( int ( n ))
print("Given 'n' numbers: ")
print(a)
m = statistics.mean ( a )
v = statistics.variance ( a )
st = statistics.stdev ( a )
print( "Mean: ",m)
print( "Variance: ",v)
print( "Standard Deviation: ",st)
OUTPUT
Enter the number of elements you want: 3
Enter numbers in array:
number : 3
number : 4
number : 5
Given 'n' numbers:
[3, 4, 5]
Mean: 4
Variance: 1
Standard Deviation: 1.0
23
Python Programming Lab(21AML38)
7b. Read a multi-digit number (as char) from the console.
Develop a program to print the frequency of each digit suitable messages.
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
num = input("Enter the multi digit number: ")
print(char_frequency(num))
OUTPUT
Enter the multi digit number: hello
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
24
Python Programming Lab(21AML38)
9a. Develop a program that uses class Students which prompts the User to enter marks in three
subjects and calculate total marks,Percentage and display the score card details. [Hint: Use list to store
the marks in three subjects and total marks. Use_init() method to initialize name, USN and the lists to
store marks and total, Use getMarks() method to read marks into the list, and display() method to
display the score card details.]
class Student:
marks = []
def __init__(self,name,rn):
self.name = name
self.rn = rn
def getMarks(self, m1, m2, m3):
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
print ("Name is: ", self.name)
print ("USN is: ", self.rn)
print ("Marks in subject 1: ", Student.marks[0])
print ("Marks in subject 2: ", Student.marks[1])
print ("Marks in subject 3: ", Student.marks[2])
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
print ("Average Marks are: ", self.average())
def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])
25
Python Programming Lab(21AML38)
def average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)
name = input("Enter the name: ")
r = input("Enter the USN: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))
s1 = Student(name,r)
s1.getMarks(m1, m2, m3)
s1.displayData()
OUTPUT
Enter the name: AKSHARA
Enter the USN: SW22AIM001
Enter the marks in the first subject: 99
Enter the marks in the second subject: 89
Enter the marks in the third subject: 88
Name is: AKSHARA
USN is: SW22AIM001
Marks in subject 1: 99
Marks in subject 2: 89
Marks in subject 3: 88
Marks are: [99, 89, 88]
Total Marks are: 276
Average Marks are: 92.0
26
Python Programming Lab(21AML38)
#10. '''Implementing program using modules and python Standard Library (pandas)'''
import pandas as pd
df = pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58], "Sex": ["male", "male", "female"],
}
)
print(df)
print(df["Age"])
ages = pd.Series([22, 35, 58], name= "age")
print(ages)
df["Age"].max()
print(ages.max())
print(df.describe())
Output
Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
0 22
1 35
2 58
Name: Age, dtype: int64
0 22
1 35
2 58
Name: age, dtype: int64
58
Age
count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
27
Python Programming Lab(21AML38)
#10.b. Implementing program using modules and python Standard Library (Numpy)
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape
a = np.arange(6)
print(a)
b=a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
28
Python Programming Lab(21AML38)
Output
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
29
Python Programming Lab(21AML38)
#10. c. Implementing program using modules and python Standard Library(Matplotlib)
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,labels=activities, colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Pie Plot')
plt.show()
Output
30
Python Programming Lab(21AML38)
#10. d. Implementing program using modules and python Standard
Library(Scipy)
import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
x1 = np.arange(6, 12)
y1 = f(x1) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', x1, y1, '--')
plt.show()
Output
31