Professional Documents
Culture Documents
Python Programming Lab (21AML38)
Python Programming Lab (21AML38)
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.’ ‘ ‘
total=m1+m2+m3
per=total/3
print("total:",total)
print("percentage:",per)
if(per>=60):
print("first division")
print("second division:")
print("third division:")
else:
print("fail...")
1
Python Programming Lab(21AML38)
OUTPUT
== case – 1==
total: 265
percentage: 88.33333333333333
first division
==case -2==
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
age=current_year-birth_year
if (age>60):
print("Senior")
else:
print("Not Senior")
OUTPUT
Not Senior
Senior
3
Python Programming Lab(21AML38)
1c . Implementing program using Strings. (Reverse, palindrome, character count, replacing characters)
def reversed_string(text):
if len(text) == 1:
return text
print(reversed_string("Python Programming!"))
def isPalindrome(s):
return s == s[::-1]
ans = isPalindrome(s)
if ans:
else:
'''CHARACTER COUNT'''
def count_chars(txt):
result = 0
return result
'''REPLACING CHARACTERS'''
print(string.replace("p", "P",1))
print(string.replace("p", "P"))
4
Python Programming Lab(21AML38)
OUTPUT
!gnimmargorP nohtyP
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
OUTPUT
6
Python Programming Lab(21AML38)
2b. Write a program to create, concatenate and print a string and accessing sub-string
OUTPUT
7
Python Programming Lab(21AML38)
2c. Write a python script to print the current date in the following format Sun May 29
import time;
ltime=time.localtime();
'''
OUTPUT
8
Python Programming Lab(21AML38)
3a. ''' Write a python program to find largest of three numbers '''
largest = num1
largest = num2
else:
largest = num3
OUTPUT
9
Python Programming Lab(21AML38)
3b. Develop a program to generate Fibonacci Sequence of length(N). Read N from the console
n1, n2 = 0, 1
count = 0
if nterms <= 0:
elif nterms == 1:
print(n1)
else:
print("Fibonacci sequence:")
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
10
Python Programming Lab(21AML38)
OUTPUT
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
except ValueError:
if k > n:
return 0
if k == 0 or k == n:
return 1
# Recursive Call
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)
#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)
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)
def voting():
try:
if age>18:
print("Eligible to vote")
else:
except:
voting()
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
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'}
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()
for i in range(int(number)):
a.append ( int ( n ))
print(a)
m = statistics.mean ( a )
v = statistics.variance ( a )
st = statistics.stdev ( a )
OUTPUT
number : 3
number : 4
number : 5
[3, 4, 5]
Mean: 4
Variance: 1
23
Python Programming Lab(21AML38)
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency(num))
OUTPUT
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
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
def total(self):
25
Python Programming Lab(21AML38)
def average(self):
s1 = Student(name,r)
s1.displayData()
OUTPUT
Marks in subject 1: 99
Marks in subject 2: 89
Marks in subject 3: 88
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)
Output
30
Python Programming Lab(21AML38)
Output
31