Python Programming Lab
LAKIREDDY BALI REDDY COLLEGE OF ENGINEERING
(AUTONOMOUS)
L.B. REDDY NAGAR, MYLAVARAM, KRISHNA DIST., A.P.-521 230.
DEPARTMENT
OF
INFORMATION TECHNOLOGY
20CS54-PYTHON PROGRAMMING LAB
[Link] SEMESTER
(R20)
A.Y:2020-2021
Python Programming LAB (20CS54)
1. Pre-requisites: C Language
2. Course Educational Objectives (CEOs):
In this course student will learn about
Student should be able to have critical understanding to do programming in PYTHON use other
higher level language compilers to carryout programming.
Course Outcomes (COs): At the end of the course, the student will be able to :
CO1: Apply building blocks of python in solving computational problems.
CO2: Implement in-built data structures available in python to solve computational problems.
CO3: Implement modular programming, string manipulations and object oriented programming in
python.
CO4: Improve individual / teamwork skills, communication & report writing skills with ethical
values.
4. Course Articulation Matrix:
Course COs Program Outcomes PSOs
Code 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 - - 2 1 - - - - - - - 3 - -
CO2 - 3 2 3 2 - - - - - - - - 3 -
20CS54
CO3 - 3 2 3 2 - - - - - - - - 3 -
CO4 - - - - - - - 2 2 2 - - - -
1 = Slight (Low) 2 = Moderate (Medium) 3-Substantial(High)
Python Programming Lab Manual
2
5. List of Experiments:
Related
SNO List of Experiments:
CO
Introduction: Language basics and example problems CO1
1 A Checking the given number is leap year or not CO1
2 B Finding the biggest number among three numbers CO1
3 C Displaying reversal of a number CO1
4 D To check given number is Armstrong or not CO1
5 E To print sum of N natural numbers CO1
6 F To check given number is palindrome or not CO1
7 G To print factorial of a number CO1
8 H To print all the prime numbers with in the given range CO1
I To calculate the series : CO1
9
S=1+x+x2+x3……………x n
J To print the following pattern : CO1
10
* *
* * *
Module-1 Exercise Programs on Lists.
11 1.A To display elements of the list in reverse order CO2
1.B Write a Python script to find the minimum and maximum CO2
12
elements without using built-in operations in the lists.
13 1.C Write a Python script to remove duplicates from a list. CO2
14 1.D Write a Python script to append a list to the second list. CO2
1.E Write a Python script to create a list with different data CO2
15
types.
Python Programming Lab Manual
3
Module-2 Exercise Programs on Tuples
16 2.A Write a Python script to find the repeated items of a tuple. CO2
2.B Write a Python script to create a tuple with different data CO2
17
types
2.C Write a Python script to replace last value of tuples in a list. CO2
Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
18
Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80,
100)]
2.D Write a Python script to sort a tuple by its float element. CO2
Sample data: [('item1', '12.20'), ('item2', '15.10'), ('item3',
19
'24.5')] Expected Output: [('item3', '24.5'), ('item2', '15.10'),
('item1', '12.20')]
Module-3 Exercise Programs on Sets and Dictionaries.
20 3.A Write a Python script to add member(s) in a set. CO2
3.B Write a Python script to perform Union, Intersection, CO2
21
difference and symmetric difference of given two sets.
3.C Write Python script to test whether every element in S is in CO2
22
T and every element in T is in S.
3.D Write a Python script to sort (ascending and descending) a CO2
23
dictionary by value.
3.E Write a Python script to check whether a given key already CO2
24
exists or not in a dictionary.
3.F Write a Python script to concatenate following dictionaries CO2
25
to create a new one.
3.G Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} CO2
26 dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4:
40, 5: 50, 6: 60}
3.H Write a Python script to print a dictionary where the keys CO2
27 are numbers between 1 and 15 (both included) and the
values are square of keys.
3.I Write a Python program to map two lists into a dictionary. CO2
28
Python Programming Lab Manual
4
Module-4 Exercise Programs on functions and recursion.
4.A Define a function max_of_three() that takes three numbers CO3
29
as arguments and returns the largest of them.
4.B Write a program which makes use of function to display all CO3
30 such numbers which are divisible by 7 but are not a multiple
of 5, between given range X and Y.
4.C Define functions to find mean, median, mode for the given CO3
31
numbers in a list.
4.D Define a function which generates Fibonacci series up to n CO3
32
numbers.
4.E Implement a python script for factorial of number by using CO3
33
recursion.
4.F Implement a python script to find GCD of given two CO3
34
numbers using recursion.
Module 5 Exercise programs on Date and Time Modules.
35 5.A Write a Python script to get the current time in Python. CO3
5.B Write a Python script to get current time in milliseconds in CO3
36
Python
5.C Write a Python script to print next 5 days starting from CO3
37
today.
Module 6 Exercise programs on Exception Handling.
6.A Write a Python script to handle simple errors by using CO3
38
exception handling mechanism
6.B Write a Python script to handle multiple errors with one CO3
39
except statement.
Module 7 Exercise programs on Strings
7.A Implement Python Script to perform various operations on CO3
40
string using string libraries.
7.B Implement Python Script to check given string is CO3
41
palindrome or not.
Python Programming Lab Manual
5
7.C Implement python script to accept line of text and find the CO3
42 number of characters, number of vowels and number of
blank spaces in it
7.D Implement python script that takes a list of words and CO3
43
returns the length of the longest one.
Module 8 Exercise programs on Regular Expressions
8.A Write a Python script to check that a string contains only a CO3
44
certain set of characters (in this case a-z, A-Z and 0-9).
8.B Write a Python script to check whether password is valid or CO3
not. Conditions for a valid password are: Should have at
45 least one number. Should have at least one uppercase and
one lowercase character. Should have at least one special
symbol. Should be between 6 to 20 characters long.
Module 9 Exercise programs on Object Oriented Programming
9.A Write a Python script to create and access class variables CO3
46
and methods.
47 9.B Write a Python script to implement method overloading. CO3
48 9.C Write a Python script to implement single inheritance. CO3
49 9.D Write a Python script to implement method overriding. CO3
Module 10 Exercise programs on Python Libraries – Numpy ,
Pandas , Matplotlib
10.A Write a NumPy program to generate a matrix product of two CO3
50
arrays.
10.B Write a NumPy program to create a random array with 1000 CO3
51 elements and compute the average, variance, standard
deviation of the array elements.
10.C Demonstrate how to download dataset and how to create CO3
DataFrame
52 i. Write a Pandas program to get the first 3 rows of a
DataFrame
ii. Write a Pandas program to select the specified columns
Python Programming Lab Manual
6
and rows from a given data frame
. iii. Write a Pandas program to select the rows where the
score is missing, i.e. is NaN.
iv. Write a Pandas program to insert a new column in
existing DataFrame.
10.D Write a Python programming to display a bar chart using CO3
53
different color for each bar.
10.E Write a Python programming to create a pie chart with a CO3
54
title.
Python Programming Lab Manual
7
BASIC EXAMPLE PROBLEMS
AIM: Implement the python program script for checking the given year is
leap year or not
PROGRAM:
y=int(input(" Entre the year :"))
if y%100==0:
if y%400==0:
print(y, "is a leap year ")
else:
print(y, "is not a leap year ")
else:
if y%4==0:
print(y," is a leap year ")
else:
print(y, "is not a leap year ")
OUTPUT:
Python Programming Lab Manual
8
AIM: Implement the python script finding biggest number among three
numbers
PROGRAM:
a=int(input("enter the first number :"))
b=int(input("enter the second number:"))
c=int(input("enter the third number :"))
if a>b and a>c :
print(" biggest =",a)
else :
if b>c :
print("biggest =",b)
else :
print("biggest =",c)
OUTPUT:
Python Programming Lab Manual
9
AIM: Implement python script for displaying the reversal of a given
number
PROGRAM:
n=int(input("enter the number :"))
print("reverse of the number =",end=" ")
while n!=0:
r=n%10
print(r, end=" ")
n=n//10
OUTPUT:
Python Programming Lab Manual
10
AIM: Implement the python script to check given number is Armstrong
number or not
PROGRAM:
n=int(input("enter the number :"))
m=n
s=0
while m!=0:
r=m%10
s=s+r**3
m=m//10
if s==n:
print(n," is a armstrong number ")
else:
print(n, "is not a armstrong number ")
OUTPUT:
AIM: Implement python script to print sum of N natural numbers
Python Programming Lab Manual
11
PROGRAM:
n=int(input("enter the number :"))
s=0
for i in range(1,n+1):
s= s+ i
print("sum of first", n, "natural numbers=",s)
OUTPUT:
Python Programming Lab Manual
12
AIM: Implement the python script to check weather the given number is
palindrome or not
PROGRAM:
n=int(input("enter the number"))
rev=0
m=n
while n!=0:
r=n%10
rev=rev*10+r
n=n//10
if rev==m:
print(m, "is a palindrome")
else:
print(m, "is not a palindrome")
OUTPUT:
Python Programming Lab Manual
13
AIM: Implement python script print factorial of a number
PROGRAM:
n=int(input("enter the number :"))
f=1
for i in range(1,n+1):
f=f*i
print("factorial of ",n ,"is=",f)
OUTPUT:
Python Programming Lab Manual
14
AIM : Implement python script to print all the prime numbers with in the
given range
PROGRAM:
n1,n2=input("Enter the range:").split()
n1=int(n1)
n2=int(n2)
print("prime numbers in the range",n1,"to",n2,"are")
for n in range(n1,n2+1):
flag=1
for i in range(2,n//2+1):
r=n%i
if(r==0):
flag=0
break
if flag==1:
print(n, end=" ")
OUTPUT:
Python Programming Lab Manual
15
AIM: Implement python script to calculate the series:
S=1+x+x2+x3…………….xn
PROGRAM:
x=int(input("enter the x value:"))
n=int(input("enter the n value:"))
e=1
s=1
while e<=n:
s=s+x**e
e=e+1
print ("sum of the series=",s)
OUTPUT:
Python Programming Lab Manual
16
AIM: Implement python script to print following pattern
* *
* * *
PROGRAM:
n=int(input("Enter [Link] lines : "))
for l in range(1,n+1):
print(" "*(n-l),end='')
print("* "*l)
OUTPUT:
MODULE-1 PROGRAM 1.A
Python Programming Lab Manual
17
AIM: Implement python script to display elements of list in reverse order.
PROGRAM:
l=list(input("Enter the list values : ").split())
[Link]()
print(" Elements of the list in reverse order are: ",end=' ')
for i in l:
print(i,end=' ')
OUTPUT:
Python Programming Lab Manual
18
MODULE-1 PROGRAM 1.B
AIM: Implement python script to find minimum and maximum elements
without using built-in operations in the lists.
PROGRAM:
l=list(map(int,input("Enter list values : ").split()))
minimum=maximum=l[0]
for i in l:
if i>maximum:
maximum=i
if i<minimum:
minimum=i
print("Minimum Element in the list = ",minimum)
print("Maximum Element in the list = ",maximum)
OUTPUT:
Python Programming Lab Manual
19
MODULE-1 PROGRAM 1.C
AIM: Implement python script to remove duplicates from a list.
PROGRAM:
l=list(input("Enter list values : ").split())
l1=[]
for i in l:
if i not in l1:
[Link](i)
print("List after deleting duplicate values is ")
for i in l1:
print(i,end=' ')
OUTPUT:
Python Programming Lab Manual
20
MODULE-1 PROGRAM 1.D
AIM: Implement python script to append a list to the second list.
PROGRAM:
l1=list(input(" Enter Elements of first list : ").split())
l2=list(input(" Enter Elements of second list : ").split())
print("Concatenated list is : ")
for i in l2:
[Link](i)
print(l1)
OUTPUT:
Python Programming Lab Manual
21
MODULE-1 PROGRAM 1.E
AIM: Implement python script to count the number of strings in a list
where the strings in a list where the string length is 2 or more.
PROGRAM:
l=list(input("Enter list of strings : ").split())
c=0
for i in l:
if len(i)>=2:
c=c+1
print(" [Link] strings of length 2 or more =",c)
OUTPUT:
Python Programming Lab Manual
22
MODULE-2 PROGRAM 2.A
AIM: Implement python script to create a tuple with different data types.
PROGRAM:
n=input(" Enter Your Name : ")
m=int(input("Enter marks in Python Subject : "))
res=bool(input(" Passed in the subject ( Y/N) : "))
a=float(input(" Enter your Average Marks : "))
t=(n,m,res,a)
print("The tuple With Different types is : ",t)
OUTPUT:
MODULE-2 PROGRAM 2.B
Python Programming Lab Manual
23
AIM: Implement python script to find the repeated items of a tuple.
PROGRAM:
t=tuple(input("Enter the tuple values : ").split())
res=[]
rep=[]
print("Repeated Elements in the Tuple Are : ",end=' ')
for i in t:
if i in res:
if i not in rep:
[Link](i)
else:
[Link](i)
for i in rep:
print(i,end=' ')
OUTPUT:
MODULE-2 PROGRAM 2.C
Python Programming Lab Manual
24
AIM: Implement python script to replace last value of tuples in a list.
PROGRAM:
n=int(input("Enter number of tuple to create : "))
l=[]
for i in range(n):
print("Enter Elements of %d tuple : "%(i+1),end=' ')
t=tuple(input().split())
[Link](t)
r=input(" Enter element to replace : ")
l2=[]
for i in l:
s=len(i)
l1=list(i)
l1[s-1]=r
[Link](tuple(l1))
print("original list is : ",l)
print("List after replacing last element of each tuple is : ",l2)
OUTPUT:
MODULE-2 PROGRAM 2.D
AIM: Implement python script to sort a tuple by its float element.
PROGRAM:
Python Programming Lab Manual
25
n=int(input("Enter number of tuple to create : "))
l=[]
for i in range(n):
print("Enter Elements of %d tuple : "%(i+1),end=' ')
t=tuple(input().split())
[Link](t)
print(sorted(l, key = lambda x: float(x[1]), reverse = True))
OUTPUT:
Python Programming Lab Manual
26
MODULE-3 PROGRAM 3.A
AIM: Implement python script to add members in a set
PROGRAM:
S=set()
n=int(input("Enter the number of elments in a set :"))
for i in range(n):
num=input("enter the element : ")
[Link](num)
print(" The set of elements are :",S)
OUTPUT:
MODULE-3 PROGRAM 3.B
Python Programming Lab Manual
27
AIM: Implement python script to perform union, Intersection, Difference
of given two sets
PROGRAM:
s1=set(input("Enter the elements of the first set :").split())
s2=set(input("Enter the elements of the second set :").split())
print("elements of the first set :",s1)
print("elements of the second set :",s2)
print("Union of (S1,S2) is :",s1|s2)
print("Intersection of s1&s2 is :",[Link](s2))
print("Difference of s1-s2 is :",s1-s2)
print("Symmetric Difference of (s1,s2) is :",s1^s2)
OUTPUT :
MODULE-3 PROGRAM 3.C
Python Programming Lab Manual
28
AIM: Implement the python script to check whether every element in S is
in T and every element in T is in S
PROGRAM:
S=set(input("Enter the elements of the set S :").split())
T=set(input("Enter the elements of the set T :").split())
for i in S:
flag=True
if i not in T:
flag=False
break
for i in T:
flag1=True
if i not in S:
flag1=False
break
if flag==True:
print("S is a subset of T")
else:
print("S is not a subset of T")
if flag1==True:
print("T is a subset of S")
else:
print("T is not a subset of S")
OUTPUT:
Python Programming Lab Manual
29
MODULE -3 PROGRAM 3.D
PROGRAM: Implement python script to sort (ascending and descending) a
dictionary by values.
Python Programming Lab Manual
30
n=int(input("Enter No Of Students : "))
markdict={}
for i in range(n):
sname,marks=input("Enter name and marks of %d student :
"%(i+1)).split()
markdict[sname]=int(marks)
marklist=list([Link]())
marklist1 = sorted([Link](), key=lambda x:x[1])
l=len(marklist)
for i in range(l-1):
for j in range(l-i-1):
if marklist[j][1]<marklist[j+1][1]:
t=marklist[j]
marklist[j]=marklist[j+1]
marklist[j+1]=t
sortdict=dict(marklist)
print(" Data in sorted ( Descending ) order : ",sortdict)
sortdict=dict(marklist1)
print(" Data in sorted ( Ascending ) order : ",sortdict)
OUTPUT:
Python Programming Lab Manual
31
MODULE-3 PROGRAM 3.E
AIM: Implement python script to check whether a given key already exists
or not in a dictionary.
Python Programming Lab Manual
32
PROGRAM:
n=int(input("Enter No Of Objects in Dictionry : "))
d={}
for i in range(n):
k,v=input("Enter key and value of %d object : "%(i+1)).split()
d[k]=v
skey=input("Enter the key search : ")
if skey in [Link]():
print(" Key Exist in the Dictionary the corresponding value of
the key is : ",d[skey])
else:
print(" Key Doesn't exist in the dictionary ")
OUTPUT:
Python Programming Lab Manual
33
MODULE-3 PROGRAM 3.F
AIM: Implement python script to concatenate following dictionaries to
create new one.
Sample Dictionary: dic1={1:10,2:20} dic2={3:30,4:40}
dic3={5:50,6:60}
Expected Result: {1:10, 2:20,3:30, 4:40, 5:50, 6:60}
PROGRAM:
d1={1:10, 2:20}
d2={3:30, 4:40}
d3={5:50, 6:60}
d={}
for i in (d1,d2,d3):
[Link](i)
print(" Dictionary1 : ",d1)
print(" Dictionary2 : ",d2)
print(" Dictionary3 : ",d3)
print(" The Concatenated Dictionary is : ",d)
OUTPUT:
Python Programming Lab Manual
34
MODULE-3 PROGRAM 3.G
AIM: Implement python script to print a dictionary where the keys are
numbers between 1 and 15 and the values are squares of keys.
PROGRAM:
d={n:n*n for n in range(1,16)}
print("Required dictionary : ",d)
OUTPUT:
Python Programming Lab Manual
35
MODULE-3 PROGRAM 3.H
AIM: Implement python script to map two lists into a dictionary.
PROGRAM:
l=list(input("Enter list of subjects : ").split())
m=list(input("Enter marks in each subject : ").split())
d=dict(zip(l,m))
print(" mapping of two lists into dictionary is : ",d)
OUTPUT:
Python Programming Lab Manual
36
MODULE-3 PROGRAM 3.I
AIM: To define a function max_of_three() that takes three numbers as
arguments and returns the largest of them.
PROGRAM:
def max_of_three(a,b,c):
if a>b and a>c:
return a
elif b>c:
return b
else:
return c
a,b,c=map(int,input("Enter any three values : ").split())
m=max_of_three(a,b,c)
print(" Largest number = ",m)
OUTPUT:
Python Programming Lab Manual
37
MODULE-4 PROGRAM 4.A
AIM: Which makes use of function to display all such numbers which are
divisible by 7 but are not a multiple of 5, between given range X and Y.
PROGRAM:
x,y=map(int,input(' Enter Range : ').split())
n=[]
for i in range(x,y+1):
if (i%7==0) and (i%5!=0):
[Link](str(i))
print('numbers Divisible by 7 and not a multiple of 5 in the range are
')
print(', '.join(n))
OUTPUT:
Python Programming Lab Manual
38
MODULE-4 PROGRAM 4.B
AIM: Define functions to find mean, median, mode for the given numbers
in a list.
PROGRAM:
def mean(a):
s=sum(a)
m1=s/len(a)
print("Mean is : ",m1)
def median(a):
[Link]()
n=len(a)
if n%2==0:
m2=(a[n//2]+a[(n-1)//2])/2
else:
m2=a[(n-1)//2]
print ("Median is : ",m2)
def mode_list(a):
d={}
for i in a:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
Python Programming Lab Manual
39
val=max(list([Link]()))
l=[]
for k,v in [Link]():
if v==val:
[Link](k)
print("Mode : ",l)
lst=list(map(int,input(" Enter List Of Values : ").split()))
mean(lst)
median(lst)
mode_list(lst)
OUTPUT:
Python Programming Lab Manual
40
MODULE-4 PROGRAM 4.C
AIM: Define a function, which generates Fibonacci series up to n numbers.
PROGRAM:
def fib(n):
if n==0 or n==1:
return n
return fib(n-1)+fib(n-2)
n=int(input('enter the [Link] terms : '))
print(' Fibonacci series upto %d terms'%n)
for i in range(n):
f=fib(i)
print(f,end=' ')
OUTPUT:
Python Programming Lab Manual
41
MODULE-4 PROGRAM 4.D
AIM: Implement a python script for factorial of number by using
recursion.
PROGRAM:
def fact(n):
if n==0:
return 1
return n*fact(n-1)
n=int(input(" Enter the number : "))
f=fact(n)
print(" Factorial of %d = %d"%(n,f))
OUTPUT:
Python Programming Lab Manual
42
MODULE-4 PROGRAM 4.F
AIM: Implement a python script to find GCD of given two numbers using
recursion.
PROGRAM:
def GCD(x,y):
if x==y:
return x
elif x>y:
return GCD(x-y,y)
else:
return GCD(x,y-x)
a,b=map(int,input(" Enter any two numbers : ").split())
g=GCD(a,b)
print("GCD of %d ,%d is %d"%(a,b,g))
OUTPUT:
Python Programming Lab Manual
43
MODULE-5 PROGRAM 5.A
AIM: Implement a python script to get the current time in Python.
PROGRAM:
from datetime import datetime
d=[Link]()
d1=[Link]('%H:%M:%S')
print(" Current Time = ",d1)
OUTPUT:
Python Programming Lab Manual
44
MODULE-5 PROGRAM 5.B
AIM: Implement a python script to get current time in
milliseconds in Python.
PROGRAM:
from datetime import datetime
d = [Link]()
print(" Current Time = ",[Link]('%H:%M:%S'))
ms=([Link]*60*60+[Link]*60+[Link])*1000+[Link]//1000
print("Current time in milliseconds = ",ms)
OUTPUT:
Python Programming Lab Manual
45
MODULE-5 PROGRAM 5.C
AIM: Implement a python script to print next 5 days starting
from today.
PROGRAM:
from datetime import datetime,timedelta
base = [Link]()
print(" Todays Date is : ",[Link]('%d-%m-%Y'))
print(" Next FIve Days dates are : ")
for x in range(1,6):
d=base + timedelta(days=x)
print([Link]('%d-%m-%Y'))
OUTPUT:
Python Programming Lab Manual
46
MODULE-6 PROGRAM 6.A
AIM: Implementation of Python script to handle simple errors by using
exception-handling mechanism.
PROGRAM:
try:
a=int(input(" Enter First Value : "))
b=int(input(" Enter the second Value : "))
print(" Sum = ",a+b)
print(" Quotient = ",a//b)
print(" Average = ",(a+b)/2.0)
except ZeroDivisionError:
print(" Division is not possible because the denominator is Zero
")
except ValueError:
print(" please provide integer value only")
else:
print(" Operation Completed Without Exception ")
try:
print(" Difference = ",a-b)
print(" Product = ",a*b)
except NameError as msg:
print(" Error is : ",msg)
finally:
print(" Possible Arithmetic operations completed ")
OUTPUT:
Python Programming Lab Manual
47
Python Programming Lab Manual
48
MODULE-6 PROGRAM 6.B
AIM: Implementation of Python script handle multiple errors with one
except statement.
PROGRAM:
try:
l=['item0','item1','item2']
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a//b
print("a//b = %d"%c)
print(" list item is : ",l[c])
except Exception as e:
print("Error is : ",e)
else:
print("No Exception Occured")
OUTPUT:
Python Programming Lab Manual
49
MODULE-7 PROGRAM 7.A
AIM: Implementation of python Script to perform various operations on
string using string libraries.
PROGRAM:
# String methods
s=input(" Enter the string : ")
print(" Changing Case of a stirng ")
print(s," In Lower Case : ",[Link]())
print(s," In Upper case : ",[Link]())
print(s," In Change Case : ",[Link]())
print(s," In Title() form : ",[Link]())
print(s," In Capitalize() form : ",[Link]())
ss=input( " Enter the substring : ")
flag=[Link](ss)
if flag==True:
print(s," starts with ",ss)
else:
print(s, " not starts with ",ss)
flag=[Link](ss)
if flag==True:
print(s," ends with ",ss)
else:
print(s, " not ends with ",ss)
print("Different words of the string are : ")
l=[Link]()
for i in l:
print(i)
print(" Joining words with --> ")
print('-->'.join(l))
print(" Display 'LBRCE' with justification methods ")
print(" 'LBRCE' after left justify with width 15 is :
","LBRCE".ljust(15,'-'))
print(" 'LBRCE' after right justify with width 15 is
:","LBRCE".rjust(15,'-'))
print(" 'LBRCE' after center justify with width 15 is
:","LBRCE".center(15,'-'))
Python Programming Lab Manual
50
s2=" This is Python Class "
print("Apply strip methods on :",s2)
print(s2," After strip() :",[Link]())
print(s2," After lstrip() :",[Link]())
print(s2," After rstrip() :",[Link]())
print(" FIND / REPLACE methods on string ")
s3=input(" Enter Some String with repeted words in it : ")
s4=input(" ENter the repeted word : ")
p=-1
while True:
p=[Link](s4,p+1,len(s3))
if p==-1:
break
print(s4, " found at position ",p," in ",s3)
print("{} Occurs {} in the {}".format(s4,[Link](s4),s3))
s5=input(" Enter the word to replace : ")
print(s3, " after replace is : ",[Link](s4,s5))
ch=input("Enter any character:")
if [Link]():
print("Alpha Numeric Character")
if [Link]():
print("Alphabet character")
if [Link]():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif [Link]():
print("It is space character")
else:
print("Non space Special Character")
Python Programming Lab Manual
51
OUTPUT:
MODULE-7 PROGRAM 7.B
AIM: Implementation of python Script to check given string is palindrome
or not.
PROGRAM:
Python Programming Lab Manual
52
s=input("Enter the String : ")
s1=s[::-1]
print(" Reverse of string is : ",s1)
if s==s1:
print(s," is a Palindrome String")
else:
print(s," is Not a Palindrome String")
OUTPUT:
Python Programming Lab Manual
53
MODULE-7 PROGRAM 7.C
AIM: Implementation of python script to accept line of text and find the
number of characters, number of vowels and number of blank spaces in it.
PROGRAM:
s=input("Please Enter line of Text : ")
cvol=0
cspace=0
cc=0
for ch in s:
cc=cc+1
if (ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' or ch=='A'
or ch=='E' or ch=='I' or ch=='O' or ch=='U'):
cvol = cvol + 1
elif ch==' ':
cspace = cspace + 1
print("Number of Vowels in the Text = ",cvol)
print("Number of spaces = ",cspace)
print("Number of characters = ",cc)
OUTPUT:
Python Programming Lab Manual
54
MODULE-7 PROGRAM 7.D
AIM: Implementation of python script that takes a list of words and
returns the length of the longest one.
PROGRAM:
l=input("Enter List Of Words : ").split()
llw=0
for w in l:
if len(w) > llw:
llw = len(w)
print(" Length of Longest word = ",llw)
print(" The Longest words are : ")
for w in l:
if len(w)==llw:
print(w)
OUTPUT:
Python Programming Lab Manual
55
MODULE-8 PROGRAM 8.A
Aim: Write a Python script to check that a string contains only a certain set
of characters (in this case a-z, A-Z and 0-9).
Program:
Import re
def is_alnum(s):
m=[Link]("[a-zA-Z0-9]*",s)
if m!= None:
print("String is formed with specified pattern")
else:
print("String is not formed with specified pattern ")
s=input("Enter the String : ")
is_alnum(s)
Output:
MODULE-8 PROGRAM 8.B
Python Programming Lab Manual
56
Aim: Write a Python script to check whether password is valid or not.
Conditions for a valid password are:
Should have at least one number.
Should have at least one uppercase and one lowercase character.
Should have at least one special symbol.
Should be between 6 to 20 characters long.
Program:
import re
password=input(" Enter the Password : ")
flag = 0
while True:
if len(password)<6 or len(password)>20:
flag=-1
break
elif not [Link]("[a-z]", password):
flag = -1
break
elif not [Link]("[A-Z]", password):
flag = -1
break
elif not [Link]("[0-9]", password):
flag = -1
break
elif not [Link]("[^a-zA-Z0-9]", password):
flag = -1
break
elif [Link]("\s", password):
flag = -1
break
else:
flag = 0
print("Valid Password")
break
if flag ==-1:
print("Not a Valid Password")
Output:
Python Programming Lab Manual
57
MODULE-9 PROGRAM 9.A
Aim: Write a python script to Create &access class variables and methods
Python Programming Lab Manual
58
Program:
class Robot:
population=0
what="Humanoid Robot"
version=1.0
speed="1THZ"
memory="1ZB"
def _init_(self, name):
[Link] = name
print('\n < Initialising ',[Link],' > ')
[Link] += 1
def _del_(self):
print([Link] , ' is being destroyed!\n')
[Link] -= 1
if [Link] == 0:
print([Link] ,' was the last one.')
else:
print(' \n There are still ', [Link] ,' robots working.')
def update(cls):
[Link]=2.0
[Link] = "2THZ"
[Link]="2ZB"
def sayHi(self):
print("\nHai i am a : ",[Link])
print("My Name is : ",[Link])
print("Version : ",[Link])
print("Speed : ",[Link])
print("Memory : ",[Link])
def howMany():
print('\n No of Robots Available curruently : ',[Link])
d=Robot('Chitti')
[Link]()
[Link]()
d1=Robot('Vennela')
Python Programming Lab Manual
59
[Link]()
[Link]()
[Link]()
print("\nRobots can do some work here.\n")
print("\nRobots have finished their work. So let's destroy them.\n")
del d
del d1
[Link]()
Output:
MODULE-9 PROGRAM 9.B
Aim: Write a python script to implement method overloading
Program:
from multipledispatch import dispatch
Python Programming Lab Manual
60
@dispatch(int,int)
def product(first,second):
result = first*second
print(" Product of two integers = ",result)
@dispatch(int,int,int)
def product(first,second,third):
result = first * second * third
print(" Product of three integers = ",result)
@dispatch(float,float,float)
def product(first,second,third):
result = first * second * third
print(" Product of three floats = ",result)
product(2,3)
product(2,3,2)
product(2.2,3.4,2.3)
Output:
MODULE-9 PROGRAM 9.C
Aim: Write a python script to implement single heritance
Program:
Python Programming Lab Manual
61
class Parent:
def __init__(self,fname,fage):
[Link]=fname
[Link]=fage
def view(self):
print([Link] , [Link])
class Child(Parent):
def __init__(self , fname , fage):
Parent.__init__(self, fname, fage)
[Link]="Internet"
def view(self):
print("course name" , [Link] ,"first came",
[Link] , " years ago." , [Link], " has courses to master
python")
ob = Child("Python" , '28')
[Link]()
Output:
MODULE-9 PROGRAM 9.D
Aim: Write a python script to implement method overriding
Program:
class Bank:
def getroi(self):
return 10
Python Programming Lab Manual
62
class SBI(Bank):
def getroi(self):
return 7
class ICICI(Bank):
def getroi(self):
return 8
class Axis(Bank):
def display(self):
print("Axis Bank Rate of interest:",[Link]())
b1 = Bank()
b2 = SBI()
b3 = ICICI()
b4 = Axis()
print("Bank Rate of interest:",[Link]())
print("SBI Rate of interest:",[Link]())
print("ICICI Rate of interest:",[Link]())
[Link]()
Output:
MODULE-10 PROGRAM 10.A
AIM : Write a NumPy program to generate a matrix product of two
arrays.
PROGRAM 12.1 :
import numpy as np
x =[Link](1,10,(3,3))
Python Programming Lab Manual
63
y =[Link](1,10,(3,3))
print("First Matrix is :")
print(x)
print("Second matrix is :")
print(y)
print("Matrix product of two Matrices:")
#print([Link](x, y))
print(x @ y)
OUTPUT :
MODULE-10 PROGRAM 10.B
AIM : Write a NumPy program to create a random array with 1000
elements and compute the average, variance, standard deviation of the
array elements.
Mean is average of element. Where 0 <= i < n
Mean of arr[0..n-1] = ∑(arr[i]) / n
Python Programming Lab Manual
64
Variance is the sum of squared differences from the mean divided by
a number of elements.
Variance = ∑(arr[i] – mean)2 / n
Standard Deviation is the square root of the variance.
Standard Deviation = √variance
Example :
Array = [6 5 3 4 2] sum=20 average or Mean = 20/5 = 4
variance=((6-4)2+(5-4)2+(3-4)2+(4-4)2+(4-2)2)/5 =
(4+1+1+0+4)/5=10/5=2
std=sqrt(2)=1.414
PROGRAM :
import numpy as np
x = [Link](1,100,1000)
print(" Elements are : ")
print(x)
print("Average of the array elements:")
mean = [Link]()
print(mean)
print("Standard deviation of the array elements:")
std = [Link]()
print(std)
print("Variance of the array elements:")
var = [Link]()
print(var)
OUTPUT :
Python Programming Lab Manual
65
MODULE-10 PROGRAM 10.C
Python Programming Lab Manual
66
AIM : Demonstrate how to download dataset and how to create DataFrame
i. Write a Pandas program to get the first 3 rows of a DataFrame
ii. Write a Pandas program to select the specified columns and rows
from a given data frame.
iii. Write a Pandas program to select the rows where the score is
missing, i.e. is NaN.
iv. Write a Pandas program to insert a new column in existing
DataFrame.
PROGRAM :
I. Write a Pandas program to get the first 3 rows of a DataFrame
import pandas as pd
import numpy as np
exam_data = {'name': ['Hema', 'Latha', 'Reddy', 'Jay', 'Madhu'],
'score': [90, 70, [Link], [Link], 30 ],
'attempts': [1,2,1,1,1],
'qualify': ['yes', 'yes', 'no', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e']
df = [Link](exam_data , index=labels)
print("First three rows of the data frame:")
print([Link][:3])
II. Write a Pandas program to select the specified columns and rows
from a given data frame.
print("Select specific columns and rows:")
print([Link][[1, 3, 5, 6], [1, 3]])
III. Write a Pandas program to select the rows where the score is
missing, i.e. is NaN.
print("Rows where score is missing:")
print(df[df['score'].isnull()])
IV. Write a Pandas program to insert a new column in existing
DataFrame.
color =
['Red','Blue','Orange','Red','White','White','Blue','Green','Green','Red']
df['color'] = color
Python Programming Lab Manual
67
print("\nNew DataFrame after inserting the 'color' column")
print(df)
OUTPUT :
MODULE-10 PROGRAM 10.D
AIM : Write a Python program to display a bar chart using different color
for each bar.
PROGRAM :
import [Link] as plt
Python Programming Lab Manual
68
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
[Link](x_pos, popularity, color=['red', 'black', 'green', 'blue', 'yellow',
'cyan'])
[Link]("Languages")
[Link]("Popularity")
[Link]("PopularitY of Programming Language\n" + "Worldwide, Oct
2017 compared to a year ago")
[Link](x_pos, x)
plt.minorticks_on()
[Link](which='major', linestyle='-', linewidth='0.5', color='red')
[Link](which='minor', linestyle=':', linewidth='0.5', color='black')
[Link]()
OUTPUT :
MODULE-10 PROGRAM 10.E
AIM : Write a Python programming to create a pie chart with a title.
PROGRAM 12.5 :
import [Link] as plt
# Plot data
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
Python Programming Lab Manual
69
#colors = ['red', 'gold', 'yellowgreen', 'blue', 'lightcoral', 'lightskyblue']
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b"]
# explode 1st slice
explode = (0, 0.1, 0, 0, 0, 0)
# Plot
[Link](popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
[Link]("PopularitY of Programming Language\n" + "Worldwide, Oct
2017 compared to a year ago", bbox={'facecolor':'0.8', 'pad':5})
[Link]()
OUTPUT :
Python Programming Lab Manual
70