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

Subject Title:Python Programming Lab Practice Branch:Dcme SUBJECT CODE:18CM-508P (A) SEM:5 Shift:2

This document outlines 51 Python programming lab programs covering topics such as: 1) Different ways to execute Python scripts and check if Python is installed 2) Demonstrating various Python data types, operators, and built-in functions 3) Creating and manipulating common Python data structures like lists, tuples, sets, dictionaries 4) Defining functions with different argument types and recursion 5) Object oriented programming concepts like classes, inheritance, polymorphism 6) Packages and modules in Python

Uploaded by

mr copy xerox
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
375 views

Subject Title:Python Programming Lab Practice Branch:Dcme SUBJECT CODE:18CM-508P (A) SEM:5 Shift:2

This document outlines 51 Python programming lab programs covering topics such as: 1) Different ways to execute Python scripts and check if Python is installed 2) Demonstrating various Python data types, operators, and built-in functions 3) Creating and manipulating common Python data structures like lists, tuples, sets, dictionaries 4) Defining functions with different argument types and recursion 5) Object oriented programming concepts like classes, inheritance, polymorphism 6) Packages and modules in Python

Uploaded by

mr copy xerox
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 180

SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME

SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2


S.N PROGRAM PAGE.NO
O
1 Write the command to check whether python interpreter is installed or 1
not.
2 Execute Python Script (Command Prompt, Script and IDLE) in 2-5
different ways.
3 Python program to demonstrate different data types in python. 6
4 Python program to type of each variable where five variables are 7
initialized with different types of value.
5 Python program to perform arithmetic operations 8
6 Python program to perform operations using logical, bitwise and 9
relational operators.
7 Python program to find largest among 3 and 4 numbers. 10
8 Python program to find the gross salary of the employee based on 11
sales done.
9 Python program to print the grade of a student. 12
10 Python program to print prime numbers upto 100. 13
11 Python program to find reverse of a number and check for palindrome. 14
12 Python program to find sum of numbers upto n. 15
13 Python program to check for Armstrong number. 16
14 Python program to find factorial of a number and Fibonacci series 17
upto n.
15 Python program to find LCM and GCD of 2 numbers. 18
16 Python program to print patterns. 19-22
17 Python program to create a List and perform following operations on 23-26
it.
18 Python program to perform addition, multiplication and transpose 27-29
operations on 3X3 matrix.
19 Python program to create a Tuple and perform operations on it. 30-33
20 Python program to create a Set and perform operations on it. 34-36
21 Write a python program to create a Dictionary and perform following 37-39
operations on it.
22 Python program to create a String and perform operations on it. 40-42
23 Python program to define functions with five different types of 43-44
arguments i.e. default arguments, keyword arguments, positional
arguments, arbitrary positional arguments, arbitrary keyword
arguments.

S.N PROGRAM PAGE.NO


O
24 Python function that finds the sum of any number of numbers. 45
25 Python script that finds the sum of n natural numbers using recursion 46

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
26 Python script that finds the factorial of a number using iterative 47
approach and recursive approach.
27 Python function calculator() such that it can accept two variables and 48
calculate the addition, subtraction, multiplication, division and
remainder of it. And also it must return all results in a single return
call.
28 Python scripts with functions that checks whether the number is 49-50
perfect, prime and palindrome or not.
29 Python scripts with functions to display Fibonacci numbers using both 51-52
iterative approach and recursive approach
30 Python program to create a class called employee with different 53-54
variables id, name, salary to hold the details of the employees, display
function that display the details, an update function that any number of
fields of an employee and a class variable that count the number of
employees. Details of the employees to be initialized with the
constructor only.
31 Python program to illustrate single inheritance. 55
32  Python program to illustrate multiple inheritance. 56
33 Python program to illustrate multilevel inheritance. 57
34 Python program that illustrates how constructors are called in a 58
multilevel inheritance.  
35  Python program with variables to the A class, which are then inherited 59
into the child class, class B. Mr. XYZ have his own variables but also
inherits from class B. write a function in XYZ have his own variables
of Mr. XYZ. Mention the type of inheritance should be employed
here.

36 Python program where a child inherits the attributes and function from 60-61
both father and mother. Add additional attributes and functions for the
child class. Call all the methods and display all the attributes of the
child class along with the inherited attributes using the child class
object. Mention the type of inheritance should be employed here.

S.N PROGRAM PAGE.NO


O
37 Python program to Define a person with the attributes name, age and 62-64
gender and a method display details function. Then define 3 different
classes namely pilot, teacher and a doctor that inherits person class,
add to these classes respectively attributes and methods. Name the
type of inheritance that should be employed in this case.
38 A person has 2 kids, each kid have their own attributes and the 65-66
inherited. Display the details of both the kids along with the inherited

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
ones. Mention the type of inheritance should be employed here
39 Consider a scenario where bank is a class that provides functionality to 67-68
get the rate of interest. However, the rate of interest varies according
to banks. For example, SBI, ICICI and axis banks could provide 8%,
7% and 9% rate of interest. Write a python program that overrides the
get interest_rate functionality in the bank class for each of the banks to
calculate the interest amounts. Mentioned the type of inheritance
should be employed here.

40 Python program to access super class constructor and methods using 69


super call method.

41 Python program using id and type operator on class instance 70


42 Python program to illustrate identity operators (is and is not) 71
43 Python program to create a module with three functions i.e. to find 72-74
factorial of a number, Fibonacci series of given number and to check
number is prime number or not and import this module in another
program using import statement and from...import statements.
44 Create a package named Cars with three modules Bmw_car.py, 75-76
Audi_car.py and Nissan_car.py with three seperate classes BMW,
Audi, Nissan with attributes and methods. Write a python program to
access the Cars package using import statement and from...import
statements.
45 Python program to Create a package called college with three different 77-79
modules student_admin.py, teacher_admin.py, computerlab_admin.py,
__init__.py , where each module holds a separate class namely
Student, Teacher and Computerlab. Define these classes with
attributes and methods (Student: name, pin, age; Teacher: name,
subject, time; ComputerLab: name, time). Import these modules by
using import statement into the package named collegedata with three
modules namely admission.py where student takes the admission,
teaching.py where faculty mapped with a particular subject and test.py
where a student takes his online test.
46 Python program to Create a package called college with three different 80-82
modules student_admin.py, teacher_admin.py, computerlab_admin.py,
__init__.py , where each module holds a separate class namely
Student, Teacher and Computerlab. Define these classes with
attributes and methods (Student: name, pin, age; Teacher: name,
subject, time; ComputerLab: name, time). Import these modules by
using from...import statement into the package named collegedata with
three modules namely admission.py where student takes the
admission, teaching.py where faculty mapped with a particular subject
and test.py where a student takes his online test.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
47 Python program to install package globally 83
48 Python program to use local and global variables in the same program. 84
49 Python program to use local and global variables as function 85
parameters.
50 Python program where first function swaps the global variable with 86
the local variable and the next function return the cube root of the new
global variable value.
51 Write the steps to install, create, enable and disable virtual 87
environment in the following platforms A.WindowsB.Linux
52 Write the commands to install, uninstall the following packages 88-89
a. numpy b. matplotlib c. seaborn d. pandas e. scikit-learn f. plotly
53 Python program to take a list of values and perform operations using 90
math functions
54 Python program to show Graphical representation of sin and cos 91-92
waves using sin() and cos() functions of math module.
55 Python program for given angles in degrees 0, 300,600, 900, 1200, 93-94
1800, 2100, 2400, and 3600.  
A.  Calculates the sine and cosine of above angles
B.  Create a list that contains the converted angles values into
gradient. 
C.  Finds floor value of sine of above angles
D.  Finds Ceiling value of cosine of above angles
E.  Finds absolute value of cosec of above angles
S.N PROGRAM PAGE.NO
O
56 Python script to display the following 95
a) Current date and time
b) Current year
c) Month of year
d) Week number of the year
e) Weekday of the week
f) Day of year
g) Day of the month
h) Day of week

57 Python program to convert a string to datetime using strptime() 96


function.
Sample String : Jan 1 2014 2:43PM
Expected Output : 2014-07-01 14:43:00
58 Python that calculates from your date of birth 97
a. Number of Years you lived
b. Number of Months you lived
c. Number of days you lived

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
59 Python script that calculates number of days to your next birthday and 98-99
on which week day your next birthday will happen.
60 Python program that calculates the retirement age of a person. A 100
person retires from the service if he attains the age of 60 years or 33
years of service whichever is earlier. Give the following input from
the keyboard
1. Date of Birth
2. Date of Joining the Service
61 If a Student joins the College on X day and leaves the college on Y 101
day. Calculate the Numbers of years, months and days a student
studies in the college.
62 Python program to catch ZeroDivisionError, ValueError and 102
NameError in three separate except blocks.
63 Python program with error block and finally block. 103
64 Python program where try block is given inside another block. 104
65 Python program to raise an exception. 105
66 Python program to create user defined exception. 106

S.N PROGRAM PAGE.NO


O
67 Python program to Create three threads where each thread is 107-108
implemented with three functions in a class.
--> First thread calculates the square of numbers from 1 to 10.
--> Second thread calculates the square root of numbers from 11 to 20.
--> Third thread calculates the cube root of numbers from 21 to 30.

68 Python program Create three threads and implement the each 109-110
functionality in the run method of three thread classes in a threading
module.
--> First thread calculates the square of numbers from 1 to 10.
--> Second thread calculates the square root of numbers from 11 to 20.
--> Third thread calculates the cube root of numbers from 21 to 30.
69 Python program to Create Multiple threads which perform different 111
tasks using threading module.
70 Python program to Design threads using start(), join(), isAlive(), 112-113
getName(), setName(), activeCount() and currentThread() methods
71 Python program to achieve thread synchronization in multithreaded 114-115
environment.
72 Python program to provide synchronize access to the global variable 116-117
balance representing the balance in your father bank account where
three threads namely father, mother and you trying to depositing an
amount, checking the balance and you performing the withdrawal
through an ATM respectively

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
73 Design the following GUIs using pack geometry managers and make 118-119
sure that the size of widget changes as the size of the container widget.
74 Design the following GUI using Grid geometry Manager 120
75 Design the following GUI using Grid geometry Manager 1211
76 Design the following GUI using Place geometry Manager 122-1231
77 Python program that display message in a message box when click on 124
a red button.
78 Python program with a canvas widget that displays various 125
geometrical shapes.
79 Python program that accepts two numbers from the entry widget and 126-127
display their sum, difference, multiplication, division and remainder in
result entry box when clicking on corresponding buttons.

S.N PROGRAM PAGE.NO


O
80 Python program with checkbutton widget that asks the programmer to 128-129
select the programming languages he knows and a button which when
clicked displays the languages known to the programmer in the
messagebox widget.
81 Python program with radiobutton widget that asks the user to select his 130
gender and a button which when clicked display his gender in the
messagebox widget.
82 Python program with frame widget. 131-132
83 Python program with Label Frame widget 133
84 Python program with Listbox widget. 134
85 Python program to create a window with a menu bar and sub menu 135-136
items using Menu widget.
86 Python program with Message widget. 137
87 Python program with OptionMenu widget. 138
88 Python program with PanedWindow widget. 139
89 Python program with Scale widget. 140
90 Python program with Scrollbar widget. 141
91 Python program with Spinbox widget. 142
92 Python program with Text widget. 143
93 Python program with Toplevel widget. 144
94 Python program to handle mouse events. 145
95 Python program to handle key board events. 146
96 Python program with a regular expression to validate a phone number. 147
A phone number of DDD-DDDD-DDD form where D stands for a
digit.
97 A. Write a python program that finds all the occurrences of a string of 148-149
a particular pattern in a file using findall() function in re module.
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
A. Write a python program that finds and replaces all the occurrences
of a string of a particular pattern with another string using sub()
function in re module.
C. Write a python program that splits the string at every occurrence of
the sub-string and returns a list of strings which have been split using
split() function in re module.
D. Write a python program to search for a character or sub-string
using search() and match() functions in re module.
98 Python program that validates the email id. 150
99 Python program that validates the IP address 151
100 Python program that validates your PIN number. 152

S.N PROGRAM PAGE.NO


O
101 Python program to show various ways to read and write data in a file 153-154
102 Python program to copy one file into another. 155
103 Python program to count the number of lines, number of words and 156-157
the number of characters in the file.
104 Python program that appends all the contents of one file at the end of 158-159
another file.
105 Python program to rename and delete a single file 160
106 Python program to remove an empty folder and folder that contains 161
files or sub folders.

107 Python program that performs CRUD operations on a student 162-163


table(name,pin,age) with a primary key.
108 Python program that executes stored procedures 164
109 Python program that stores images and files in a table. 165-166
110 Write the steps to enable I2C and SPI interface in Raspbian Operating 167-168
system PI board using the command prompt and GUI.
111 Write the steps to configure the circuit and python program to turn on 169-170
and turn off LED.
112 Write the steps to configure the circuit and python program to make a 171-172
buzzer playing sound using the buzzer.
113 Write the steps to connect the Raspberry PI board to the internet using 173
WIFI network.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

1.Aim:Write the command to check whether python interpreter is installed or not.


Program:
1. Open Command Prompt > Type Python Or py> Hit Enter If Python Is Installed
it will show the version Details Otherwise It will Open Microsoft Store To
Download From Microsoft Store
2. Just go in cmd and type where python if it installed it will open a prompt.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 1
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
2. Aim: Execute Python Script (Command Prompt, Script and IDLE) in different ways.
There are three different ways of working in Python:
1. Command Prompt or Interactive Mode.
2. Script Mode.
3. IDLE Mode.
1. Command Prompt or Interactive Mode: Go to the python installation location (for
example, C: Users\user\AppData\Local\Programs\Python\Python38) and you can enter
python.exe in the command prompt and start working with Python. Python comes with an
interactive interpreter. When you type python in your shell or command prompt, the python
interpreter becomes active with a >>> prompt and waits for your commands.

Press Enter key and the Command Prompt will appear like:

Now you can execute your Python commands. Now you can type any valid python
expression at the prompt. Python reads the typed expression, evaluates it and prints the
result.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 2
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

2. Script Mode: Using Script Mode, you can write your Python code in a separate file using
any editor of your Operating System.

Save the file in any folder (Ex : Desktop) with any name and an extension of (a.py).
Now open Command prompt and run this program by calling python a.py

3. Using IDE (Integrated Development Environment) : IDLE short for Integrated


Development Environment or Integrated Development and Learning Environment. IDLE
is a deveSlopment environment for Python Programming. An IDE combines a program
editor and a language environment as a convenience to the programmer.
You can execute your Python code using a Graphical User Interface (GUI).
All you need to do is:
Click on Start button -> All Programs -> Python -> IDLE (Python GUI)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 3
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

You can use both Interactive as well as Script mode in IDE.

i) Using Interactive Mode : Execute your Python code on the Python prompt and it will
display the result simultaneously.

(ii) Using Script Mode: Click on Start button -> All Programs -> Python -> IDLE (Python
GUI). Python Shell will be opened.
Got File menu click on New File (CTRL+N) and write the code and save add.py
a=input("Enter a value: ")
b=input("Enter b value: ")
c=int(a)+int(b)
print("The sum is, c)

And run the program by pressing F5 or Run -> Run Module.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 4
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 5
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
3. Aim: Write a python program to demonstrate different data types in python.
Program:
a=10
b=10.2
c=10.5556783666546733
d=100000000000000
e="vishnu"
f='c'
g=2+3j
h=a>b
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
Save:- “datatype.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 6
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
4. Aim: Write a python program to type of each variable where five variables are
initialized with different types of value.
Program:
a = 10
print (type(a))
a = 12.3
print(type(a))
a = 'hi'
print(type(a))
a = 12 > 9
print(type(a))
a = 2 + 3j
print(type(a))
Save: - “datatype1.py”
Run: - F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 7
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
5. Aim: Write a python program to perform arithmetic operations.
Program:
#python program on arithmetic operations
a=10
b=20
'''addition'''
c=a+b
print("addition: ",c)
'''subtraction'''
c=a-b
print("subtraction: ",c)
'''multiplication'''
c=a*b
print("multiplication: ",c)
'''division'''
c=a//b
print("division: ",c)
'''modulus'''
c=a%b
print("modulus: ",c)
'''exponent'''
c=a**b
print("exponent: ",c)
Save:- “arithop.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 8
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
6. Aim: Write a python program to perform operations using logical, bitwise and
relational operators.
Program:
a,b=int(input("enter a numbers:")),int(input("enter another number(b):"))
print(a,">",b,"=",(a>b))
print(a,"<",b,"=",(a<b))
print(a,">=",b,"=",(a>=b))
print(a,"<=",b,"=",(a<=b))
print(a,"==",b,"=",(a==b))
print(a,'!=',b,"=",(a!=b))
print(a,'>',b,'and',a,'<',b,'=',(a>b and a<b))
print(a,'>',b,'or',a,'<',b,'=',(a>b or a<b))
print('not (',a,'>',b,') =',not(a>b))
print(a,"&",b,"=",(a&b))
print(a,"|",b,"=",(a|b))
print(a,"^",b,"=",(a^b))
print(a,">>",b,"=",(a>>b))
print(a,'<<',b,"=",(a<<b))
Save:- “relatop.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 9
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
7.Aim:Write a python program to find largest among 3 and 4 numbers.
Program:
n=int(input("enter no.of input numbers (3,4) = "))
if n==3:
a,b = int(input("enter a value = ")),int(input("enter b value = "))
c = int(input("enter c value = "))
if a >= b and a >= c:
print(a, "is greatest")
elif b >= c:
print(b, "is greatest")
else:
print(c, "is greatest")
else:
a,b = int(input("enter a value = ")), int(input("enter b value = "))
c,d = int(input("enter c value = ")), int(input("enter d value = "))
if a >= b and a >= c and a >= d:
print(a, "is greatest")
elif b >= c and b >= d:
print(b, "is greatest")
elif c >= d:
print(c, "is greatest")
else:
print(d, "is greatest")
Save:- “big.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 10
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
8.Aim:Write a Python program to find the gross salary of the employee based on sales
done.
Program:
base=int(input("enter base salary = "))
sales=int(input("enter no. of sales = "))
if sales<=10:
gross=base*10
print("salary = ",gross)
elif sales<=50:
gross=base*15
print("salary = ",gross)
elif sales<=100:
gross=base*20
print("salary = ",gross)
else:
gross=base*25
print("salary = ",gross)
Save:- “gross.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 11
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
9.Aim: Write a python program to print the grade of a student.
Program:
name=input("enter name = ")
gpa=float(input("enter gpa = "))
print("student details are")
print("Name:",name)
print("Gpa:",gpa)
print("Grade of the student:")
if gpa>9.0:
print("A+")
elifgpa>8.0:
print("A")
elifgpa>7.0:
print("B+")
elifgpa>6.0:
print("B")
elifgpa>5.0:
print("C+")
elifgpa>4.0:
print("C")
elifgpa==4.0:
print("D")
else:
print("E")
Save:- “grade.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 12
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
10.Aim:Write a python program to print prime numbers upto 100.
Program:
n=int(input("enter the n value:"))
print("prime numbers upto ",n)
count = 0
for i in range(2,n+1):
count=0
for j in range(1,i+1):
if i%j==0:
count+=1
if count==2:
print(i)
Save:- “prime.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 13
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
11.Aim:Write a python program to find reverse of a number and check for palindrome.
Program:-
n=int(input("enter a number = "))
last=0;rev=0;temp=0
temp=n
while(n!=0):
last=n%10
rev=rev*10+last
n=n//10
print("reverse of given number is",rev)
if temp==rev:
print(temp,"is a palindrome")
else:
print(temp,"is not a palindrome")
Save:- “reverse.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 14
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
12.Aim:Write a python program to find sum of numbers upto n.
Program:
n=int(input("enter the n value:"))
sum=0
for i in range(sum,n+1):
sum=sum+i
print("sum of numbers upto",n,"=",sum)
Save:- “sum.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 15
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
13.Aim:Write a python program to check for Armstrong number.
Program:
num=int(input("enter the num:"))
sum=0
x=num
n=len(str(num))
while num>0:
d=num%10
num=num//10
sum=sum+pow(d,n)
if x==sum:
print(x,"is an armstong number")
else:
print(x, "is not an armstong number")
Save:- “sum.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 16
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
14.Aim: Write a python program to find factorial of a number and Fibonacci series
upto n.
Program:
def fact(n):
if n==1:
return 1
else:
return n*fact(n-1) #fact(5)
n=int(input("enter n value = "))
print(n,"!","=",fact(n))
a=0
b=1
c=0
while(c<=n):
print(c)
c=a+b
a,b=b,c
Save:- “fibfac.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 17
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
15.Aim: Write a python program to find LCM and GCD of 2 numbers.
Program:
n1=int(input("enter number1 = "))
n2=int(input("enter number2 = "))
if(n1>n2):
numerator=n1
denominator=n2
else:
denominator=n1
numerator=n2
rem=numerator % denominator
while(rem!=0):
numerator=denominator
denominator=rem
rem=numerator% denominator
gcd=denominator
lcm=(n1*n2)//gcd
print("The lcm of the given numbers is =",lcm)
print("The gcd of the given numbers is =",gcd)
Save:- “lcmgcd.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

16.Aim: Write a python program to print patterns.


(a) *
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 18
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
**
***
****
*****

(b) ******
*****
****
***
**
*

(c) 1
121
12321
1234321
123454321

(d) 1
12
123
1234
123
12
1

(e) $****
*$ *
* $ *
* $*
****$

(f) ***
*
***

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 19
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
*
***
(g) A
BC
DEF
GHIJ
KLMNO
Program:
print("(A)")

for i in range(1,6):
print("* "*i)
print()
print("(B)")
k=3
for i in range(5,-1,-1):
for j in range(k,0,-1):
print(end=' ')
k=k+1
for j in range(0,i+1):
print("*",end=' ')
print(' ')
print("(C)")
for i in range(6):
for j in range(1,i+1):
print(j,end=' ')
if(i==j):
for x in range(i-1,0,-1):
print(x,end=' ')
print()
print("(D)")
for i in range(5):
for j in range(1,i+1):
print(j,end=' ')
print()
for i in range(4,0,-1):
for j in range(1,i):
print(j,end=' ')

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 20
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print()

print("(E)")
for i in range(1,6):
for j in range(1,6):
if i==j:
print("$",end=" ")
elifi==1 or j==1 or i==5 or j==5:
print("*",end=" ")
else:
print(" ",end=" ")
print(" ")
print("(F)")
for i in range(1,6):
for j in range(1,4):
if i==2 and j==1:
print("*",end=' ')
elifi==4 and j==3:
print("*",end=' ')
elifi==1 or i==3 or i==5:
print("*",end=" ")
else:
print(" ",end=" ")
print(" ")

print("(G)")
a=65
for i in range(5):
for j in range(i+1):
print(chr(a),end=' ')
a+=1
print()
print()
Save:- “lcmgcd.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 21
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 22
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
17.Aim:Write a python program to create a List and perform following operations on
it.
(i) Create a list in different ways.
(ii) Process the list using the following functions.
(iii) Perform the following operation on the list (a)del an element (b)append an
element (c)clear the list (d)delete the list (e)remove (f)pop
(iv) Perform the operation on the on the list using the following function (a)index
(b)count (c)copy
(v) Slice the list in different ways.
(vi) Given lists L1 and L2 find 2L1+3L2
(vii) Create a 3X3 matrix from a given list of nine elements.
(viii) Write a python program to get the frequency of the elements in a list.
(ix) Write a python function that takes two lists and returns true if they have at
least one common member.
Program:
l1=[1,2,3,4,1,1,3,1,2]
l2=[4,5,6]
l3=[3,6,2,1,4,0]
l4=[2,3,4]
print("----create list in different ways----")
clist=[]
print(clist)
print("enter 5 list elements:")
for a in range(5):
ele=int(input())
clist.append(ele)
print(clist)
lst= [18, 19, 21]
print(lst)
mixed_list = [11, 'Eleven', True]
print(mixed_list)
print("----performing different operations on list----")
del l3[0]
print(l3)
l3.append(7)
print(l3)
l3.clear()
print(l3)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 23
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
l4.remove(3)
print(l4)
l4.pop(1)
print(l4)
del l4
#list l4 has been deleted and gives error when you try to print it.
print(l1.index(4))
print(l1.count(1))
print(l1.copy())
print("----Slice the list in different ways.----")
print(l1[::])
print(l1[1:6])
print(l1[3:10:2])
print(l1[::2])
print(l1[:0:])
print(l1[-7:-1])
print(l1[-1::-1])
print("----find 2l1+3l2----")
result=(2*l1)+(3*l2)
print(result)
print("----3X3 matrix from a given list of nine elements.----")
mat=[]
n=0
for i in range(3):
p=[]
for j in range(3):
ele=l1[n]
p.append(ele)
n += 1
mat.append(p)
for i in range(3):
for j in range(3):
print(mat[i][j],end=" ")
print()
print("----frequency of the elements in a list.----")
# importing the module
import collections
# initializing the list

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 24
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
l = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']
# using Counter to find frequency of elements
frequency = collections.Counter(l)
# printing the frequency
print(dict(frequency))
print("----return true if there is at least one common element----")
def compare(l1,l2):
for x in l1:
for y in l2:
if x==y:
return 'True'
else:
return 'False'print(compare(l1,l2))
Save:- “list.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 25
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 26
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
18.Aim: Write a python program to perform addition, multiplication and transpose
operations on 3X3 matrix.
Program:
a=[]
b=[]
c=[]
d=[]
e=[]
print("enter elements of first matrix")
for i in range(3):
p=[]
for j in range(3):
p.append(int(input()))
a.append(p)
print("enter elements of second matrix")
for i in range(3):
p=[]
for j in range(3):
p.append(int(input()))
b.append(p)
for i in range(3):
p=[]
for j in range(3):
p.append(a[i][j] +b[i][j])
c.append(p)
print("Addition of two matrices is")
for i in range(3):
for j in range(3):
print(c[i][j],end=' ')
print()
for i in range(3):
p=[]
for j in range(3):
s=0
for k in range(3):
s=s+(a[i][k] * b[k][j])
p.append(s)
d.append(p)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 27
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print("Multiplication of two matrices is")
for i in range(3):
for j in range(3):
print(d[i][j],end=' ')
print()
for i in range(3):
p=[]
for j in range(3):
p.append(a[j][i])
e.append(p)
print("Transpose of first matrix is")
for i in range(3):
for j in range(3):
print(e[i][j],end=' ')
print()
Save:- “18.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 28
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

19.Aim:Write a python program to create a Tuple and perform following operations on


it.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 29
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
(i) Create a tuple with mutable and immutable objects
(ii) Update an element of a list inside the Tuple.
(iii) Write a python program to unpack a tuple into several variables.
(iv) Write a python program to convert a list into a tuple.
(v) Write a python program to slice a Tuple in different ways.
(vi) Python program to reverse a tuple.
(vii) Process the Tuple using the following functions
(a)all
(b)enumerate
(c)sorted
(d)tuple
(e)max
(f)any
(viii) Write a Python program to count the elements in a list until an element is a Tuple.
program:-
# 1. mutable and immutable objects
t =("name", [1,2,3,4])
#here we cannot change the "name" & add additional string to it
# but we can change the list in the tuple
print(t) # before change of list
print(id(t))
t[1][3] = 5
print(t) #after change of list
print(id(t))
#2.update
t[1].append(6)
print(t)
print(id(t))
# 3.unpack a tuple in variables
tuplex = 4, 8, 3
print(tuplex)
n1, n2, n3 = tuplex
print(n1 + n2 + n3)
#4.Convert list to tuple
listx = [5, 10, 7, 4, 15, 3]
print(listx)
tuplex = tuple(listx)
print(tuplex)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 30
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
#5.slicing the tuple
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
_slice = tuplex[3:5]
print(_slice)
_slice = tuplex[:6]
print(_slice)
_slice = tuplex[5:]
print(_slice)
_slice = tuplex[:]
print(_slice)
_slice = tuplex[-8:-4]
print(_slice)
tuplex = tuple("HELLO WORLD")
print(tuplex)
_slice = tuplex[2:9:2]
print(_slice)
_slice = tuplex[::4]
print(_slice)
_slice = tuplex[9:2:-4]
print(_slice)
#6.reversing the tuple
_tuple = (1,2,3.78, 9.56,"python")
_tuple = tuple(reversed(_tuple))
print(_tuple)
languages = ['Python', 'Java', 'JavaScript']
prime= enumerate(languages)
# 7.convert enumerate object to list
print(list(prime))
n= [4, 2, 12, 8]
sorted_num = sorted(n)
print(sorted_num)
l = [1, 3, 4, 5]
print(all(l))
l = [0, False]
print(all(l))
l = [1, 3, 4, 0]
print(all(l))
l = [0, False, 5]

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 31
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print(all(l))
l = []
print(all(l))
l = [1, 3, 4, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
num = [9, 34, 11, -4, 27]
# find the maximum number
max_num = max(num)
print(max_num)
t1 = tuple()
print('t1 =', t1)
t2 = tuple([1, 4, 6])
print('t2 =', t2)
t1 = tuple('Python')
print('t1 =',t1)
t1 = tuple({1: 'one', 2: 'two'})
print('t1 =',t1)
#8.count the elements of list until it becomes tuple
num= [10,20,30,(10,20),40]
ctr = 0
for n in num:
if isinstance(n, tuple):
break
ctr += 1
print(ctr)
Save:- “19.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 32
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 33
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
20.Aim:Write a python program to create a Set and perform following operations on it.
(i) Create a set (a) Empty Set (b) With different types of objects (c) from a list
(ii) Perform set operations (a) Union (b) Intersection (c) Difference (d) Symmetric
Difference
(iii) Use the following function (a)issubset (b) issuperset (c) isdisjoint().
(iv) Use and write the difference between using the following methods with sets (a)del
(b)pop (c)remove (d)discard
program:-
#1)create a set
#a)creating an empty set
set1=set()
print(type(set1))
#b)creating set with different types of objects
#python does not allow a set to store a list
set2={1,6.3,"abc",(1,2,3)}
print(set2)
#c)creating set from a list
list1=[1,2.4,'f',"mnop"]
set3=set(list1)
print(set3)

#2)set operations
#a)union
s1={1,2,3,4,5}
s2={9,8,7,6,5,4}
print(s1.union(s2))
print(s1|s2)
#b)intersection
print(s1.intersection(s2))
print(s1&s2)
#c)difference
print(s1.difference(s2))
print(s1-s2)
print(s2.difference(s1))
print(s2-s1)
#d)symmetric_differnce
print(s1.symmetric_difference(s2))
print(s1^s2)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 34
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

#3)set functions
set1={1,2,3,4,5}
set2={9,8,7,6,5,4}
#a)issuperset
print(set1.issuperset(set2))
print(set1>=set2)
#b)issubset
print(set1.issubset(set2))
print(set1<=set2)
#c)isdisjoint
print(set1.isdisjoint(set2))

#4)set methods
#a)pop
print(set1.pop())
print(set1)
#b)remove
print(set1.remove(3))#raises error if element is not found in set
print(set1)
#c)discard
print(set1.discard(100))#raises no error even if element is not found in set
print(set1)
#d)del
del(set1)
print(set1)#error as set1 not found

Save:- “20.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 35
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 36
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
21.Aim: Write a python program to create a Dictionary and perform following
operations on it.
(i) Write a python script to create a dictionary in different ways.
(ii) Delete elements from the dictionary
(a).del (b)pop (c)popitem
(iii)Write a python script to generate and print a dictionary that contains a number (between
1 and n) in the form (x, x*x).
Sample Dictionary (n = 5):
Expected Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
(iv)Write a python script to check whether a given key already exists in a dictionary.
(v) Write a python script to iterate over a dictionary and display
(a) only Keys (b) only values and (c) Both keys and Values
(vi) Write a python script to iterate over a nested dictionary and display
(a) only Keys (b) only values and (c) Both keys and Values
(vii) Write a Python program to map two lists into a dictionary.
(viii) Write Python Script to sort the dictionary according to the Key.
Program:
#1 creating dictionary in different ways
#empty dictionary
my_dict = {}
print(my_dict)
#dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
#dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
#using dict()
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict)
#from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict)

#2 deleting using pop,del,popitem


my_dict = {31: 'a', 21: 'b', 14: 'c'}
print(my_dict)
del my_dict[31]

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 37
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print(my_dict)
my_dict.pop(21)
print(my_dict)
my_dict.popitem()
print(my_dict)

#3. generate and print numbers and square (i, i*i)


n=5
numbers = {}
for i in range(1, n+1):
numbers[i] = i * i
print(numbers)
#4 checking key using in() function
Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
if 'a' in Fruits:
print("Key exists")
else:
print("Key does not exist")
# checking key using not in() function
if 'd' not in Fruits:
print("key does not exists")
else:
print("Key exist")
#5 print keys,values,keys and values using itertaion
for key in Fruits.keys():
print(key)
for value in Fruits.values():
print(value)
for key,value in Fruits.items():
print(key,":",value)
#6 print keys,values,keys and values using nested dictonary
d={'1':{'a':"python",'b':"java",'c':".net"},
'2':{'d':"javascript",'e':"c",'f':"shell"}}
for key in d.keys():
print(key)
for value in d.values():
print(value)
for key,value in d.items():

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 38
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print(key,":",value)
#7 mapping 2 lists into dictionary
keys = ['red', 'green', 'blue']
values = ['rose','leafs', 'sky']
dict1= dict(zip(keys, values))
print(dict1)
#8 sorting dictionary using key
a = {1:"java" ,2:"python",4:"javascript" ,3:"php" ,6:"cpp" ,5:".net" }
print(sorted(a.keys()))
Save:- “21.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

22.Aim: Write a python program to create a String and perform following operations
on it.
(i) Create string in different ways.
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 39
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
(ii) Perform slicing of string in different ways.
(iii) Process string using operator +,*, in, not in, and, and or.
(iv) Use following function to process a stringcapitalize(), title(), lower(), upper(),
swapcase(), islower(), isupper(), isdigit(), isalpha(), isalnum()
(v) Use following function to process a string count(),find(),replace(),index() (vi) Use
following function to process a string rjust(),ljust(),center(),zfill(),join() (vii) Write a
python program to display the characters that are repeated in a string also display the
times it was repeated. Example Input: i am a diploma cme student Output: i=2 a=3
m=3 d=2 e=2
(viii) Write a python program that finds the most repeated word in a given paragraph.
(ix) Write a python program that display a word, its reverse word (palindrome) if both
exists in the given paragraph.
(x) Write a python program to split the given sentence into list of words.
Program:
import collections
from collections import Counter
str1='gptcmasabtank'
str2="computer engineering"
str3='''third year fifth sem'''
print("str1:",str1)
print("str2:",str2)
print("str3:",str3)
print("---INDEXING---")
print("str1[0]:",str1[0])
print("str1[1]:",str1[1])
print("str1[-1]:",str1[-1])
print("---SLICING---")
print("str2[:]:",str2[:])
print("str2[2:5]:",str2[2:5])
print("str2[2:]:",str2[2:])
print("str2[:7]:",str2[:7])
print("str2[7:-3]:",str2[7:-3])
print("----STRING OPERATORS----")
print("concatination(+):",str1+str2)
print("repeatation of string n times(*):",str1*4)
print("in operator (a in str2):","a" in str2)
print("not in operator (g not in str1):","g" not in str1)
print("and operator (str1 and str2):",str1 and str2)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 40
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print("and operator (str1 or str2):",str1 or str2)
print("----BUILT IN FUNCTIONS----")
print("lower():",str1.lower())
print("upper():",str1.upper())
print("count('a'):",str1.count('a'))
print("swapcase():",str1.swapcase())
print("title():",str1.title())
print("islower():",str1.islower())
print("isupper():",str1.isupper())
print("isdecimal():",str1.isdecimal())
print("isdigit():",str1.isdigit())
print("isnumeric():",str1.isnumeric())
print("isalpha():",str1.isalpha())
print("isalnum():",str1.isalnum())
print("rjust():",str1.rjust(20,'*'))
print("ljust():",str1.ljust(20,'*'))
print("center():",str1.center(30,'*'))
print("zfill():",str1.zfill(20))
print("split():",str3.split())
str4=str2[::-1]
print("reverse of a string (str2[::-1]):",str4)
if str2==str4:
print("str2 string is a palindrome")
else:
print("str2 string is not a palindrome")
print("characters that are repeated in string with no, of times repeated")
frequencies=collections.Counter(str2)
repeated={}
for key,value in frequencies.items():
if value>1:
repeated[key]=value
print(repeated)
res=Counter(str2)
res=max(res,key=res.get)
print("most occuring character is:",res)
Save:- “22.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 41
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 42
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
23:Aim: Write a python program to define functions with five different types of
arguments i.e. default arguments, keyword arguments, positional arguments, arbitrary
positional arguments, arbitrary keyword arguments.
Program:
print("----Default Arguments----")
def add(a,b=5,c=10):
return (a+b+c)
print (add(2))
print(add(3,4))
print(add(2,3,4))
print("----Key Arguments----")
def sum(a,b=5,c=10):
return (a+b+c)
print(sum(b=10,c=15,a=20))
print(sum(a=10))
print("----Positional Arguments----")
def ad(a,b,c):
return (a+b+c)
print(ad(10,20,30))
print(ad(10,c=30,b=20))
print("----Arbitrary Positional Arguments----")
def asum(*b):
result=0
for i in b:
result=result+i
return result
print(asum(1,2,3,4,5))
print(asum(10,20))
print("----Arbitrary Positional Arguments----")
def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
Save:- “23.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 43
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

24.Aim: Define a function that finds the sum of any number of numbers.
Program:

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 44
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
num = int(input("Enter a number: "))
def sum(n):
result=0
for i in range(1,n+1):
result=result+i
print("sum of",n,"numbers:",result)
sum(num)
Save:- “24.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 45
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
25.Aim: Write a python script that finds the sum of n natural numbers using recursion.
Program:
#recursive
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
num = int(input("enter n value:"))
if num< 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Save:- “25.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 46
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
26.Aim: Write a python script that finds the factorial of a number using iterative
approach and recursive approach.
Program:
#using recursive function
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("Enter a number: "))
print("factorial of ",num," using recursion")
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elifnum == 0:
print("The factorial of 0 is 1")
else:
print(recur_factorial(num))

#using iteration
print("factorial of ",num," using iterative")
fac = 1
for i in range(1, num + 1):
fac = fac * i
print(fac)
Save:- “26.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 47
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
27.Aim: Write a function calculator() such that it can accept two variables and
calculate the addition, subtraction, multiplication, division and remainder of it. And
also it must return all results in a single return call.
Program:
def calculator(a,b):
add=a+b
sub=a-b
mul=a*b
div=a/b
mod=a%b
return add,sub,mul,div,mod
a=int(input("enter 1st:"))
b=int(input("enter 2nd:"))
tup=calculator(a,b)
print("add:",tup[0])
print("difference:",tup[1])
print("product:",tup[2])
print("divison:",tup[3])
print("modules:",tup[4])
Save:- “27.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 48
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
28.Aim: Write a python scripts with functions that checks whether the number is
perfect, prime and palindrome or not.
Program:
#perfect number
def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
num=int(input("enter a num:"))
print(perfect_number(num))
#prime number
def prime(num):
if num>1:
s=int(num/2)
for i in range(2,s+1):
if num%i==0:
return("not prime")
break
return("prime")
print(prime(num))
#pallindrome
temp=num
def isPalindrome(n):
reverse = 0
reminder = 0
while(n != 0):
remainder = n % 10
reverse = reverse * 10 + remainder
n = int(n / 10)
return reverse
reverse = isPalindrome(num)
if(temp == reverse):
print(temp,'is a Palindrome')
else:
print(temp,"is not a Palindrome")
Save:- “28.py”

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 49
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 50
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
29.Aim: Write a python scripts with functions to display Fibonacci numbers using both
iterative approach and recursive approach.
Program:
n=int(input("enter n value:"))
def FactRec(n):
if n==0:
return 1
return n*FactRec(n-1)
print("1.factorail of",n,"using recursion",FactRec(n))
def FactIt(n):
res=1
for i in range(2,n+1):
res*=i
return res
print("2.factorial of",n,"using iteration is:",FactIt(n))
n1,n2=0,1
count=0
if n<=0:
print("please enter a positive integer")
else:
print("3.fibonacci series upto",n,"using iteration")
while n1<n:
print(n1)
temp=n1+n2
n1=n2
n2=temp

def FibRec(n):
if n<=1:
return n
else:
return FibRec(n-1)+FibRec(n-2)
if n<=0:
print("please enter a positive integer")
else:
print("4.fibonacci series upto",n,"using recursion")
for i in range(n):
f=FibRec(i)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 51
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
if(f<=n):
print(f)
Save:- “29.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 52
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
30. Aim: create a class called employee with different variables id, name, salary to hold
the details of the employees, display function that display the details, an update
function that any number of fields of an employee and a class variable that count the
number of employees. Details of the employees to be initialized with the constructor
only.
Program:
class Employee:
counter = 0
def __init__(self, Id, name, salary):
self.Id = Id
self.name = name
self.salary = salary
Employee.counter+=1
def display(self):
print("Id:", self.Id, "\nName:", self.name, "\nSalary:", self.salary)
def update(self):
req = input("What do you want to update?: ")
if req == "Id" or req == "id":
self.Id = input("Enter Id: ")
self.display()
elifreq == "Name" or req == "name":
self.name = input("Enter Name: ")
self.display()
elifreq == "Salary" or req == "salary":
self.salary = input("Enter Salary: ")
self.display()
else:
print("Enter valid input")
self.update()

e1 = Employee(12, "alex", 9999999)


e2 = Employee(11, "steve", 9899999)
e1.display()
e2.display()
print("****Update Employee1 details****")
e1.update()
print("No. of Employees are:",Employee.counter)
Save:- “30.py”

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 53
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 54
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
31.Aim: write a python program to illustrate Single inheritance.
Program:
class base(object):
def __init__(self):
self.a = int(input("enter a value:"))
self.b = int(input("enter b value:"))
print("i am in base class ")
print("addition in base class=",self.a+self.b)

class derived(base):
def __init__(self,):
base.__init__(self)
a = int(input("enter a value:"))
b = int(input("enter b value:"))
print("i am in derived class")
print("addition in derived class=", (a + b))
obj=derived()
Save:- “31.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 55
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
32.Aim: write a python program to illustrate multiple inheritance.
Program:
class Father:
def Driving(self):
print("Father Enjoys Driving")
class Mother:
def Cooking(self):
print("Mother Enjoys Cooking")
class Child(Father, Mother):
def Playing(self):
print("Child Loves Playing")
obj = Child()
obj.Driving()
obj.Cooking()
obj.Playing()
Save:- “32.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 56
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
33.Aim: write a python program to illustrate multilevel inheritance.
Program:
class GrandFather():
def Haikid(self):
print("hai kid")
class Father(GrandFather):
def haison(self):
print("hai son")
class son(Father):
def hai(self):
print("hai")
obj = son()
obj.Haikid()
obj.haison()
obj.hai()
Save:- “33.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 57
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
34.Aim: write a python program that illustrates how constructors are called in a
multilevel inheritance.
Program:
class grand:
def __init__(self):
print("grand class constructor")
class parent(grand):
def __init__(self):
print("parent class constructor")
class child(parent):
def __init__(self):
print("child class constructor")
obj=child()
Save:- “34.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 58
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
35.Aim: write a program with variables to the A class, which are then inherited into the
child class, class B. Mr. XYZ have his own variables but also inherits from class B.
write a function in XYZ have his own variables of Mr. XYZ. Mention the type of
inheritance should be employed here.
Program:
class A:
def dataA(self):
self.name=input("enter name=")
self.pin=input("enter pin=")
class B(A):
def dataB(self):
self.gpa=float(input("enter gpa="))
self.shift=int(input("enter shift="))
class xyz(B):
def dataxyz(self):
self.clg_name=input("enter college name=")
def fun(self):
print("name=",self.name,"\n pin=",self.pin,"\n shift= ",self.gpa, "\n shift=",self.shift," \n
collage_name=",self.clg_name)
o=xyz()
o.dataA()
o.dataB()
o.dataxyz()
o.fun()
Save:- “35.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 59
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
36.Aim: write a python program where a child inherits the attributes and function
from both father and mother. Add additional attributes and functions for the child
class. Call all the methods and display all the attributes of the child class along with the
inherited attributes using the child class object. Mention the type of inheritance should
be employed here.
Program:
class father:
def __init__(self):
self.m = input("enter the father's occupation:")
self.n = float(input("enter the father's salary:"))
def occupation(self):
print("father's occupation is:",self.m)
def salary(self):
print("father's salary is:", self.n)
class mother:
def __init__(self):
self.o= input("enter the mother's occupation:")
self.p = float(input("enter the mother's salary:"))
def occupations(self):
print("mother's occupation is:",self.o)
def salarys(self):
print("mother salary is:", self.p)
class child(father, mother):
def __init__(self):
father.__init__(self)
mother.__init__(self)
q = float(input("enter the school fee:"))
def inhert(self):
print("...MULTIPLE INHERITANCE...")
def name(self):
print("name of the child is krishna")
def schlfee(self):
print("school fee of the child is:", self.q)
def incm(self):
print("income of their family per month :", self.n + self.p)
def saving(self):
print("savings of their income : ", (self.n + self.p)-self.q)
c = child()

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 60
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
c.inhert()
print("attribute of father class is", c.m ,c.n)
print("attribute of mother class is:", c.o , c.p)
print("attribute of child class is:", c.q)
c.occupation()
c.salary()
c.occupations()
c.salarys()
c.name()
c.schlfee()
c.incm()
c.saving()
Save:- “36.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 61
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
37.Aim: Define a person with the attributes name, age and gender and a method
display_details function. Then define 3 different classes namely pilot, teacher and a
doctor that inherits person class, add to these classes respectively attributes and
methods. Name the type of inheritance that should be employed in this case.
Program:
class person:
name=input("enter name:")
age=int(input("enter age:"))
gender=input("enter gender:")
def display(self):
print("name=",self.name)
print("age=",self.age)
print("gender=",self.gender)
class pilot(person):
print("")
print("Enter pilot details")
airline = input("enter the name of the airline=")
hours = int(input("enter the no. of hours ="))
hmairport = input("enter the home airport=")
dnairport = input("enter the destination airport=")
size = int(input("enter the size of flight="))
def service_pilot(self):
print("....AIRLINE.....")
print("NAME OF AIRLINE=",self.airline)
print("NO. OF HOURS=", self.hours)
print("NAME OF THE HOME AIRPORT=", self.hmairport)
print("NAME OF THE DESTINATION AIRPORT =", self.dnairport)
print("SIZE OF THE FLIGHT=", self.size)

class teacher(person):
print("")
print("")
print("Enter teacher details")
subject = input("enter the subject name=")
college = input("enter the college name=")
nstudents = int(input("enter the no. of students="))
workload = int(input("enter the no. of work done="))
semester = int(input("enter the semester="))

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 62
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
def service_teacher(self):
print(".......TEACHER.....")
print("NAME OF SUBJECT=", self.subject)
print("NAME OF COLLEGE=", self.college)
print("NO. OF STUDENTS=", self.nstudents)
print("NO. OF HOURS WORK DONE=", self.workload)
print("SEMESTER=", self.semester)
class doctor(person):
print("")
print("")
print("Enter doctor details")
hospital = input("enter the name of hospital=")
experience = int(input("enter the no. of years experience="))
special = input("enter the specilaization=")
daily = int(input("enter the no. of patients daily="))
hour = int(input("enter the no. of hours="))
def service_doctor(self):
print("NAME OF THE HOSPITAL=", self.hospital)
print("N0. OF YEARS EXPERIENCE=", self.experience)
print("SPECIALIZATION=", self.special)
print("N0. OF PATIENTS DAILY=", self.daily)
print("N0. OF HOURS WORK=", self.hour)
o=person()
o.display()
p=pilot()
t=teacher()
d=doctor()
p.service_pilot()
t.service_teacher()
d.service_doctor()
Save:- “37.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 63
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

38.Aim: a person has 2 kids, each kid have their own attributes and the inherited.
Display the details of both the kids along with the inherited ones. Mention the type of
inheritance should be employed here.
Program:
class father():

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 64
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
fheight=0

class mother():
mheight=0

class son(father,mother):
def __init__(self,sf,sm):
self.fheight=sf
self.mheight=sm
def sh(self):
print(self.fheight)
sheight=(self.fheight+self.mheight)/2
return sheight

class daughter(father, mother):


def __init__(self,sf,sm):
self.fheight=sf
self.mheight=sm
def dh(self):
dheight = (self.fheight + self.mheight)/2.3
return dheight
print("Enter father height")
sf=float(input())
print("Enter mother height")
sm=float(input())
s=son(sf,sm)
do=daughter(sf,sm)
print("Height of son= ",s.sh())
print("height of daughter= ",do.dh())

Save:- “38.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 65
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 66
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
39.Aim: consider a scenario where bank is a class that provides functionality to get the
rate of interest. However, the rate of interest varies according to banks. For example,
SBI, ICICI and axis banks could provide 8%, 7% and 9% rate of interest. Write a
python program that overrides the get_interest_rate functionality in the bank class for
each of the banks to calculate the interest amounts. Mentioned the type of inheritance
should be employed here.
Program:
class bank:
def get_interest_rate(self):
print('interest')
class sbi(bank):
def get_interest_rate(self,p,t):
print('rate of interest for the bank sbi is 8%')
print('rate of interest for the amout',p,'during ',t,'years is:',((p*t*8)/100))

class icici(bank):
def get_interest_rate(self,p,t):
print('rate of interest for the bank icici is 7%')
print('rate of interest for the amout',p,'during ',t,'years is:',((p*t*7)/100))

class axis(bank):
def get_interest_rate(self,p,t):
print('rate of interest for the bank axis is 9%')
print('rate of interest for the amout',p,'during ',t,'years is:',((p*t*9)/100))
axisobj =axis()
sbiobj=sbi()
iciciobj=icici()
p=float(input('enter principal amount:'))
t=float(input('enter time period:'))
sbiobj.get_interest_rate(p,t)
iciciobj.get_interest_rate(p,t)
axisobj.get_interest_rate(p,t)
Save:- “39.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 67
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 68
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
40.Aim: write a python program to access super class constructor and methods using
super call method.
Program:
class superclass():
def __init__(self):
print("i am a constructor in super class ")
self.a=int(input("enter a value :"))
self.b=int(input("enter b value :"))
def getdata(self):
print("iam a method in super class")
print("a+b =",(self.a+self.b))
class subclass(superclass):
def __init__(self):
super().__init__()
super().getdata()
s=subclass()
Save:- “40.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 69
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
41.Aim: write a python program using id and type operator on class instance.
Program:
a=int(input("enter a value:"))
b=int(input("enter b value:"))
class typeid:
c=a+b
print("addition: ",c)
t=typeid()
print("***ID and TYPE operators***")
print("id(t):",id(t))
print("type(t):",type(t))
Save:- “typeid.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 70
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
42.Aim: write a python program to illustrate identity operators (is and is not)
Program:
x=int(input("enter x value:"))
y=int(input("enter y value:"))
z=float(input("enter z value:"))
print("---is and is not operator---")
if(x is y):
print(x,"and",y,"are equal")
else:
print(x,"is not equal to",y)
if(z is not y):
print(z,"is not equal to",y)
else:
print(z,"is equals to ",y)
print(type(x) is not int)
print(type(z)is float)
print(type(y) is str)
Save:- “isoperat.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 71
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
43.Aim: Write a python program to create a module with three functions i.e. to find
factorial of a number, Fibonacci series of given number and to check number is prime
number or not and import this module in another program using import statement and
from...import statements.
Program:
#fact.py
def fact(num):
if(num==1):
return 1
else:
return num*fact(num-1)
#fib.py
def fib(num):
a=0
b=1
print("fibonacci series upto ",num)
if num==1:
print(a)
else:
print(a)
print(b)
for i in range(2,num):
c=a+b
a=b
b=c
print(c)
#prime.py
def prime(i,num):
if num==i:
return 0
else:
if num%i==0:
return 1
else:
return prime(i+1,num)
def call(num):
if (prime(2,num)==0):
print(num," is a prime numnber")

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 72
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
else:
print(num," is not a prime number")
#43.py
print("......using import ...")
import fact
print("factorial of 5: ",fact.fact(5))
import prime
prime.call(71)
import fib
fib.fib(10)
print("....using from import.....")
from fact import *
print("factorial of 5: ",fact(5))
from prime import *
call(71)
from fib import *
fib(10)
Save:- “43.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 73
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

44. Aim: Create a package named Cars with three modules Bmw_car.py, Audi_car.py
and Nissan_car.py with three seperate classes BMW, Audi, Nissan with attributes and

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 74
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
methods. Write a python program to access the Cars package using import statement
and from...import statements.
Program:
___init__.py
from .bmw import bmw
from .nissan import nissan
from .audi import audi
audi.py
class audi:
def __init__(self):
self.models=['y8','y9','y10']
def outmodels(self):
for x in self.models:
print(x)
bmw.py
class bmw:
def __init__(self):
self.models=['y3','y4','7']
def outmodels(self):
for m in self.models:
print(m)
nissan.py
class nissan:
def __init__(self):
self.models=['x3','x4','x7']
def outmodels(self):
for g in self.models:
print(g)
44.py
from cars import *
from cars import *
from cars import *
BMW=bmw()
BMW.outmodels()
AUDI=audi()
AUDI.outmodels()
NISSAN=nissan()
NISSAN.outmodels()

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 75
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Save:- “44.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 76
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
45. Aim: Create a package called college with three different modules
student_admin.py, teacher_admin.py, computerlab_admin.py, __init__.py , where each
module holds a separate class namely Student, Teacher and Computerlab. Define these
classes with attributes and methods (Student: name, pin, age; Teacher: name, subject,
time; ComputerLab: name, time). Import these modules by using import statement into
the package named collegedata with three modules namely admission.py where student
takes the admission, teaching.py where faculty mapped with a particular subject and
test.py where a student takes his online test.
Program:
#computer_lab.py
class computer:
def __init__(self, name, time):
self.name=name
self.time=time
def sub_test(self):
if(self.time == "11:30"):
print("You have computers test: Proceed to Google form link in the Subject group(Google
classroom/Whatsapp")
else:
print("You are either too early or late for the exam")
#student_admin.py
class Student:
def __init__(self, name, pin, age):
self.name=name
self.pin=pin
self.age=age
def admission(self):
add_date= input("What is the date of admission:")
add_time= input("What is the time of admission:")
add_fathname= input("What is your father's name:")
add_mothhname = input("What is your mother's name:")
add_fathoccp= input("What is your father's occupation:")
print("Name:",self.name)
print("Pin:",self.pin)
print("Age:",self.age)
print("Admission Date:",add_date)
print("Admission Time:",add_time)
print("Father's Name:",add_fathname)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 77
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print("Mother's Name:",add_mothhname)
print("Father's occupation:",add_fathoccp)
#teacher_admin.py
class Teacher:
def __init__(self, name, subjects):
self.name=name
self.subjects=subjects
def sub_periods(self):
if(self.subjects == "Python"):
print("Hello",self.name, "Sir, You have class on 11:30")
elif(self.subjects == "Java"):
print("Hello",self.name, "Sir, You have class on 8:30")
else:
print("Enter registered Subject")
#admission.py
import college.student_admin as a
name = input("Enter name of the student:")
pin = input("Enter pin of the student:")
age = input("Enter age of the student:")
admin = a.Student(name, pin, age)
admin.admission()
#teaching.py
import college.teacher_admin as t
name = input("Enter name of the faculty:")
subjects = input("Enter subject of the faculty:")
teach = t.Teacher(name, subjects)
teach.sub_periods()
#test.py
import college.computer_lab as c
name = input("Enter name of the student:")
time = input("Enter time of the Exam:")
cl=c.computer(name, time)
cl.sub_test()
#Main.py
import admission as admin
import teaching as teach
import test
Run:-Main.py=>F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 78
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 79
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
46. Aim: Create a package called college with three different modules
student_admin.py, teacher_admin.py, computerlab_admin.py, __init__.py , where each
module holds a separate class namely Student, Teacher and Computerlab. Define these
classes with attributes and methods (Student: name, pin, age; Teacher: name, subject,
time; ComputerLab: name, time). Import these modules by using from...import
statement into the package named collegedata with three modules namely admission.py
where student takes the admission, teaching.py where faculty mapped with a particular
subject and test.py where a student takes his online test.
Program:
#computer_lab.py
class computer:
def __init__(self, name, time):
self.name=name
self.time=time
def sub_test(self):
if(self.time == "11:30"):
print("You have computers test: Proceed to Google form link in the Subject group(Google
classroom/Whatsapp")
else:
print("You are either too early or late for the exam")
#student_admin.py
class Student:
def __init__(self, name, pin, age):
self.name=name
self.pin=pin
self.age=age
def admission(self):
add_date= input("What is the date of admission:")
add_time= input("What is the time of admission:")
add_fathname= input("What is your father's name:")
add_mothhname = input("What is your mother's name:")
add_fathoccp= input("What is your father's occupation:")
print("Name:",self.name)
print("Pin:",self.pin)
print("Age:",self.age)
print("Admission Date:",add_date)
print("Admission Time:",add_time)
print("Father's Name:",add_fathname)

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 80
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print("Mother's Name:",add_mothhname)
print("Father's occupation:",add_fathoccp)
#teacher_admin.py
class Teacher:
def __init__(self, name, subjects):
self.name=name
self.subjects=subjects
def sub_periods(self):
if(self.subjects == "Python"):
print("Hello",self.name, "Sir, You have class on 11:30")
elif(self.subjects == "Java"):
print("Hello",self.name, "Sir, You have class on 8:30")
else:
print("Enter registered Subject")
#admission.py
from college import student_admin as a
name = input("Enter name of the student:")
pin = input("Enter pin of the student:")
age = input("Enter age of the student:")
admin = a.Student(name, pin, age)
admin.admission()
#teaching.py
from college import teacher_admin as t
name = input("Enter name of the faculty:")
subjects = input("Enter subject of the faculty:")
teach = t.Teacher(name, subjects)
teach.sub_periods()
#test.py
from college import computer_lab as c
name = input("Enter name of the student:")
time = input("Enter time of the Exam:")
cl=c.computer(name, time)
cl.sub_test()

#Main.py
import admission as admin
import teaching as teach
import test

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 81
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Run:-Main.py=>F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 82
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
47. Aim: Write a python program to install package globally.
Program:
#arithop.py
def addition(a,b):
return a+b;
def subtraction(a,b):
return a-b;
def multiplication(a,b):
return a*b;
def division(a,b):
return a/b;
#arthtest.py
from arth import arthop as a
print("Enter any two numbers= ")
n1=int(input())
n2=int(input())
print(a.addition(n1,n2))
print(a.subtraction(n1,n2))
#setup.py
from setuptools import setup
setup(name="arth",
version='0.1',
description='This package performs arithmetic operations',
url='#',
author='Tauseef',
author_emial='syedtauseef2611@gmail.com',
license='GPT',
packages=['arth'],
zip_safe=False)
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

48. Aim: Write a python program to use local and global variables in the same
program.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 83
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Program:
a=1
# Uses global because there is no local 'a'
def f():
print('Inside f() : ', a)
# Variable 'a' is redefined as a local
def g():
a=2
print('Inside g() : ', a)
# Uses global keyword to modify global 'a'
def h():
global a
a=3
print('Inside h() : ', a)
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Save:- “48.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 84
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
49. Aim: Write a python program to use local and global variables as function
parameters.
Program:
def func(x,y):
global a
a=45
x,y=y,x
b=33
b=17
c=100
print(a,b,x,y)
a,b,x,y=3,15,3,4
func(9,81)
print(a,b,x,y)
Save:- “49.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 85
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

50. Aim: Write a python program where first function swaps the global variable with
the local variable and the next function return the cube root of the new global variable
value.
Program:
a = int(input("enter the global value:"))
def swapGlobal():
global a
b = int(input("enter the local value:"))
a=b
def Cube():
return a**(1/3)
swapGlobal()
print("The new global value after swapig global variable with local :",a)
print("cube root of ",a," =",Cube())
Save:- “50.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

51. Aim: Write the steps to install, create, enable and disable virtual environment in the
following platforms
A. Windows

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 86
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
B. Linux
Theory:
Windows:
Installation:
Step1: open command prompt.
Step2: check to see if your python installation has pip:
pip -h
Step3: The virtualenv package is required to create virtual environment:
pip install virtualene
Creation:
To create virtual environment, you must specify path:
virtualenvvirtualenv_name
Enable:
To activate python environment:
Virtualenv_name\scripts\activate
Disable:
To deactivate virtual environment:
deactivate
Linux:
Installation:
Step1: if pip is not in your System:
$ sudo apt-get install python-pip
Step2: then install virtualenv
$ pip install virtualenv
Step3: check your installation:
$ virtualenv –version
Creation:
To Create :
$ virtualenvvirtualenv_name
Enable:
To activate :
$ source virtualenv_name/bin/activate
Disable:
To deactivate: $ deactivate

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 87
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
52. Aim:Write the commands to install, uninstall the following packages
a. numpy
b. matplotlib
c. seaborn
d. pandas
e. scikit-learn
f. plotly
Program:
1. NUMPY
# installation of numpy
Step-1: check python version
python3 -V
Step-2: Installing of pip
python get-pip.py
Step-3: Install numpy
pip3 install numpy
Step-4: verify numpy installation
pip3 show numpy
Step-5: import the numpy package
import numpy as np
Step-6: Upgrading numpy
pip3 install --upgrade numpy
# uninstalling numpy using pip
pip3 uninstall numpy
2. MATPLOTLIB
# installing matplotlib
Step-1: Make sure python and pip are pre-installed in your system
To check python: python --version
To check pip: pip -V
Step-2: Install matplotlib
pip install matplotlib
Step-3: Check if it is installed successfully
import matplotlib
matplotlib.__version__
# uninstalling matplotlib
sudo pip uninstall matplotlib
3. SEABORN
# installation of seaborn

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 88
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Step-1: To install seaborn
pip install Seaborn
Step-2: To verify the installation
import seaborn as sns
sns.__version__
# uninstalling seaborn
pip uninstall Seaborn
4. PANDAS
# installation of pandas
pip install pandas
# uninstallation of pandas
pip uninstall pandas
5. SCIKIT-LEARN
# installation of scikit-learn
Step-1: To install scikit-learn
pip install -U scikit-learn
Step-2: To check installation
python -m pip show scikit-learn
# uninstallation of scikit-learn
pip uninstall scikit-learn --yes
6. PLOTLY
# installation of plotly
pip install plotly==5.4.0
# uninstallation of plotly
pip uninstall plotly

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 89
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
53. Aim: Write a python program to take a list of values and perform below operations
using math functions
a. ceil() b. fabs() c. factorial() d. floor() e. gcd() f. round() g. sqrt() h.
pow()
Program:
import math
a=4
b=9.25
c=10
print("___MATH FUNCTIONS___ ")
print("sqrt=",math.sqrt(a))
print("round=",round(b))
print("ceil=",math.ceil(b))
print("floor=",math.floor(b))
print("power=",math.pow(c,a))
print("factorial=",math.factorial(a))
print("gcd=",math.gcd(c,a))
print("fabs=",math.fabs(b))
Save:- “53.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

54. Aim: Write a python program to show Graphical representation of sin and cos
waves using sin() and cos() functions of math module.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 90
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Program:
# Python program showing Graphical representation of cos() function
import math
import numpy as np
import matplotlib.pyplot as plt
in_array = np.linspace(-(3 * np.pi), 3 * np.pi, 50)
out_array = []
for i in range(len(in_array)):
out_array.append(math.cos(in_array[i]))
i += 1
print("in_array : ", in_array)
print("\nout_array : ", out_array)
# red for numpy.cos()
plt.plot(in_array, out_array, color = 'red', marker = "o")
plt.title("math.cos()")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
# Python program showing Graphical representation of sin() function
import math
import matplotlib.pyplot as plt
import numpy as np
in_array = np.arange(0, 10, 0.1);
out_array = []
for i in range(len(in_array)):
out_array.append(math.sin(in_array[i]))
i += 1
print("in_array : ", in_array)
print("\nout_array : ", out_array)
# red for numpy.sin()
plt.plot(in_array, out_array, color = 'red', marker = "o")
plt.title("math.sin()")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Save:- “54.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 91
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 92
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
55. Aim: Write a python program for given angles in degrees 0, 300,600, 900, 1200,
1800, 2100, 2400, and 3600.  
A.  Calculates the sine and cosine of above angles
B.  Create a list that contains the converted angles values into gradient. 
C.  Finds floor value of sine of above angles
D.  Finds Ceiling value of cosine of above angles
E.  Finds absolute value of cosec of above angles
Program:
import math
def trigonometry(*an):
print("sine values are : ")
for i in an:
print(i," = ",math.sin(i))
print("cosine values are : ")
for i in an:
print(i," = ",math.cos(i))
print("floor values of sine having angles : ")
print("sine values are : ")
for i in an:
print(i," = ",math.floor(math.sin(i)))
print("cosine values are : ")
for i in an:
print(i," = ",math.ceil(math.cos(i)))
print("Absolute values of sine having angles : ")
for i in an:
try:
print(i," = ",abs(1/(math.sin(i))))
except ZeroDivisionError as e:
print(i," = infinite")
trigonometry(0,30,60,90,120,180,210,240,360)
Save:- “55.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 93
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 94
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
56. Aim: Write a Python script to display the following
a) Current date and time
b) Current year
c) Month of year
d) Week number of the year
e) Weekday of the week
f) Day of year
g) Day of the month
h) Day of week
Program:
import time
import datetime
print("Current date and time :",datetime.datetime.now())
print("Current year:",datetime.date.today().strftime("%Y"))
print("Current Month:",datetime.date.today().strftime("%B"))
print("Week number of the year:",datetime.date.today().strftime("%W"))
print("Weekday of the week:",datetime.date.today().strftime("%w"))
print("Day of year:",datetime.date.today().strftime("%j"))
print("Day of the month:",datetime.date.today().strftime("%d"))
print("Day of week:",datetime.date.today().strftime("%A"))
Save:- “56.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 95
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
57. Aim: Write a Python program to convert a string to datetime using strptime()
function.
Sample String : Jan 1 2014 2:43PM
Expected Output : 2014-07-01 14:43:00
Program:
import datetime
def convert(date_time):
format = '%b %d %Y %I:%M%p'
datetime_str = datetime.datetime.strptime(date_time, format)
return datetime_str
date_time = 'Jul 14 2003 3:43PM'
print(convert(date_time))
Save:- “57.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

58. Aim: Write a python that calculates from your date of birth
a. Number of Years you lived

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 96
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
b. Number of Months you lived
c. Number of days you lived
Program:
from datetime import date
d1=date(2021,11,19)
d2=date(2003,7,14)
duration=(d1-d2)
print("from 14/7/2003 to 19/11/2021 :")
print(" total Days = ",duration.days)
years=duration.days // 365
months= (duration.days ) // 30
print("years = ",years)
print("months = ",months)
Save:- “58.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

59. Aim: Write a python script that calculates number of days to your next birthday
and on which week day your next birthday will happen.
Program:
from datetime import datetime
def get_user():

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 97
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
year=int(input("When is your birthday? [Y][Y]"))
month=int(input("When is your birthday? [M][M]"))
day=int(input("When is your birthday? [D][D]"))
birthday=datetime(year,month,day)
return birthday

def calculate(birthday):
now=datetime.now()
delta1=datetime(now.year, birthday.month, birthday.day)
delta2=datetime(now.year+1, birthday.month, birthday.day)
weekday=delta2.weekday()
print("Your birthday will be on ", end="")
if weekday == 0:
print("Monday")
elif weekday == 1:
print("Tuesday")
elif weekday == 2:
print("Wednesday")
elif weekday == 3:
print("Thursday")
elif weekday == 4:
print("Friday")
elif weekday == 5:
print("Saturday")
elif weekday == 6:
print("Sunday")
return((delta1 if delta1 > now else delta2)-now).days

bd = get_user()
c=calculate(bd)
print("Days left till your birthday:",c)
Save:- “59.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 98
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

60. Aim: Write a python program that calculates the retirement age of a person. A
person retires from the service if he attains the age of 60 years or 33 years of service
whichever is earlier. Give the following input from the keyboard
1. Date of Birth
2. Date of Joining the Service
Program:
from datetime import date

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 99
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print("enter date of birth of that person YYYY MM DD:")
d1=date(int(input("year:")),int(input("month:")),int(input("day:")))
print("enter date of joining of work of that person YYYY MM DD:")
d2=date(int(input("year:")),int(input("month:")),int(input("day:")))
d=date.today()
m=(d-d1)
n=(d-d2)
age=m.days//365
service=n.days//365
print("age=",age)
print("service=",service)
if age>=60 or service>=33:
print("this person has to retire")
else:
print("he or she can still work")
Save:- “60.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

61. Aim: If a Student joins the College on X day and leaves the college on Y day.
Calculate the Numbers of years, months and days a student studies in the college.
Program:
from datetime import date
d1=date(2022,1,24)
d2=date(2019,6,1)
duration=(d1-d2)
print("from 1/6/2019 to 24/1/2022 :")
print(" total Days = ",duration.days)
years=duration.days // 365

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 100
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
months= (duration.days - years*365) // 30
print("years = ",years)
print("months = ",months)
Save:- “61.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

62. Aim: write a program to catch ZeroDivisionError, ValueError and NameError in


three separate except blocks.
Program:
try:
print("try block")
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
except ZeroDivisionError as e:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
print(e)
except ValueError as v:

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 101
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
print(" except ValueError block")
print("Invalid value is given")
print(v)
except NameError as n:
print("except NameError block")
print("Variable must be initialized before accessing")
print(n)
finally:
print("finally block")
z=x/y
print("division=",z)
Save:- “62.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

63. Aim: Write a program with error block and finally block.
Program:
def divide(x, y):
try:
result=x // y
except ZeroDivisionError:
print("Sorry! You are dividing by zero")
except ValueError:
print("correct value should be given")
except NameError:
print("this name is not defined")
else:
print("Yeah! Your answer is :",result)
finally:
print("this is always executed ")
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 102
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
divide(3,2)
divide(3,0)

Save:- “63.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

64. Aim: Write a python program where try block is given inside another block.
Program:
try:
a=1,2,3,4,5
print(a[5])
try:
x=a[2]//0
except ZeroDivisionError:
print("division by zero is not possible")
except IndexError:
print(" IndexError")
print("Element at such index does not exist")
Save:- “64.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 103
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 104
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
65. Aim: Write a python program to raise an exception.
Program:
num=int(input("Enter a number= "))
if num<0:
raise Exception("Only positive integers allowed")
else:
print("You entered",num)
Save:- “65.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 105
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
66. Aim:  Write a python program to create user defined exception.
Program:
class MyException(Exception):
def __int__(self,arg):
self.args=arg
def abc(self,dict):
for i,j in dict.items():
print("NAME=",i,"BALANCE=",j)
#print(self.args)
if j<2000.00:
raise MyException('warning!...... bank Balance is less in the account of',i)

obj=MyException()
bank={"ravi":5000.00,"ramu":8500.00,"raju":1990.00}
try:
obj.abc(bank)
except MyException as e:
print(e.args)

Save:- “66.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 106
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
67. Aim: Create three threads where each thread is implemented with three functions
in a class.
--> First thread calculates the square of numbers from 1 to 10.
--> Second thread calculates the square root of numbers from 11 to 20.
--> Third thread calculates the cube root of numbers from 21 to 30.
Program:
import time
import math
class demo:
def sqr(self,n):
for x in n:
time.sleep(1)
print("square of a number",x,"is:",x*x)
def sqrt1(self,n):
for x in n:
time.sleep(1)
print("square root of a number",x,"is : ",math.sqrt(x))
def cube(self,n):
for x in n:
time.sleep(1)
print("cube of a number",x,"is:",x*x*x)
d=demo()
n1=[1,2,3,4,5,6,7,8,9,10]
start =time.time()
d.sqr(n1)
end=time.time()
n2=[11,12,13,14,15,16,17,18,19,20]
start =time.time()
d.sqrt1(n2)
end=time.time()
n3=[21,22,23,24,25,26,27,28,29,30]
start =time.time()
d.cube(n3)
end=time.time()
print("Total timetaken for execution is:",end-start)
Save:- “67.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 107
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 108
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
68. Aim: Create three threads and implement the each functionality in the run method
of three thread classes in a threading module.
--> First thread calculates the square of numbers from 1 to 10.
--> Second thread calculates the square root of numbers from 11 to 20.
--> Third thread calculates the cube root of numbers from 21 to 30.
Program:
import time
import math
def sqr(n):
for x in n:
time.sleep(1)
print("square of a number",x,"is:",x*x)
n=[1,2,3,4,5,6,7,8,9,10]
start =time.time()
sqr(n)
end=time.time()
def sqrt(n):
for x in n:
time.sleep(1)
print("square root of a number",math.sqrt(x))
n=[11,12,13,14,15,16,17,18,19,20]
start =time.time()
sqrt(n)
end=time.time()
def cube(n):
for x in n:
time.sleep(1)
print("cube of a number",x,"is:",x*x*x)
n=[21,22,23,24,25,26,27,28,29,30]
start =time.time()
cube(n)
end=time.time()
print("Total timetaken for execution is:",end-start)
Save:- “68.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 109
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 110
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
69. Aim: Create Multiple threads which perform different tasks using threading
module.
Program:
import threading
from threading import *
import time
def sqr(n):
for x in n:
time.sleep(0)
print("Square of number ",x,"is:",x*x)
def cube(n):
for x in n:
time.sleep(1)
print("Cube of number ",x,"is:",x*x*x)
n=[1,2,3,4,5,6,7,8]
start=time.time()
t1=Thread(target=sqr,args=(n,))
t2=Thread(target=cube,args=(n,))
t1.start()
t2.start()
time.sleep(1)
t1.join()
t2.join()
end=time.time()
print("Total time taken for execution is:",end-start)
Save:- “69.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 111
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
70. Aim: Design threads using start(), join(), isAlive(), getName(), setName(),
activeCount() and currentThread() methods.
Program:
#thread methods
import time
import threading
from threading import Thread
def sleepme(i):
print("thread %i going to sleep for 2 seconds." %i)
print(threading.currentThread().getName())
time.sleep(2)
print("thread %i is awake now" %i)
print("thread %s is awake now" % threading.currentThread())
print(threading.currentThread().getName(),'starting')
"""def worker():
print(threading.currentThread().getName(),'starting')
time.sleep(3)"""

for i in range(5):
th=Thread(target=sleepme,args=(i,))
th.setName('first thread')
th.start()
print(th.isAlive())
th.join()
print(th.isAlive())
print("current thread count:%i" % threading.activeCount())

Save:- “70.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 112
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 113
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
71. Aim: Write a python program to achieve thread synchronization in multithreaded
environment.
Program:
from threading import *
print("")
class Table:
def printTable(self,number):
for i in range(1,11):
print("",number,' x ',i,' = ',number*i)

class Mythread(Thread):
def __init__(self,tobj,number):
Thread.__init__(self)
self.tobj=tobj;
self.number=number
def run(self):
lock.acquire()
self.tobj.printTable(self.number)
lock.release()
lock=Lock()
tobj=Table()
t1=Mythread(tobj,100)
t2=Mythread(tobj,200)
t3=Mythread(tobj,300 )
t1.start()
t2.start()
t3.start()
Save:- “71.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 114
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 115
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
72. Aim: Write a python program to provide synchronize access to the global variable
balance representing the balance in your father bank account where three threads
namely father, mother and you trying to depositing an amount, checking the balance
and you performing the withdrawal through an ATM respectively.
Program:
from threading import *
bal=1500
def deposit(n):
global bal
bal=bal+n
print(" succcesfully deposited :",n)
def bal_enquiry():
global bal
print(" Available bal :",bal)
def withdraw(n):
global bal
if(n<=(bal-500)):
bal=bal-n
print(" successfully withdrawn :",n)
else:
print("Enter the amount which is less than your balance ")
def thread_task():
lock.acquire()
print("Executing ",current_thread().getName()," :")
choice=int(input(" select 1.deposit 2.bal_enquiry 3.withdraw "))
if (choice==1):
d=int(input("Enter the money to be deposited :"))
deposit(d)
elif (choice==2):
bal_enquiry()
else:
d=int(input("Enter the money to be drawn :"))
withdraw(d)
lock.release()

lock=Lock()
t1=Thread(target=thread_task)
t1.setName("Father")

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 116
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
t2=Thread(target=thread_task)
t2.setName("Mother")
t3=Thread(target=thread_task)
t3.setName("Child")
t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()
print("End of the program.....")

Save:- “72.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

73. Aim:Design the following GUIs using pack geometry managers and make sure that
the size of widget changes as the size of the container widget.
A.                               B.  

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 117
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

Program:
73A.py
from tkinter import *
win=Tk()
b1=Button(win,text="ALL IS WELL").pack(fill=BOTH,expand=True)
b2=Button(win,text="BACK TO BASICS").pack(fill=BOTH,expand=True)
b3=Button(win,text="CATCH ME IF U CAN").pack(fill=BOTH,expand=True)
b4=Button(win,text="LEFT").pack(side=LEFT,fill=BOTH,expand=True)
b5=Button(win,text="CENTER").pack(side=LEFT,fill=BOTH,expand=True)
b6=Button(win,text="RIGHT").pack(side=LEFT,fill=BOTH,expand=True)
win.mainloop()
73B.py
from tkinter import *
win=Tk()
topframe=Frame(win)
topframe.pack(side=TOP,expand=True,fill=BOTH)
bottomframe=Frame(win)
bottomframe.pack(side=BOTTOM,expand=True,fill=BOTH)
b1=Button(topframe,text="red",bg="red",fg="white").pack(side=LEFT,fill=BOTH,expand=
True)
b2=Button(topframe,text="blue",bg="blue",fg="white").pack(side=LEFT,fill=BOTH,expand
=True)
b3=Button(topframe,text="green",bg="green",fg="white").pack(side=LEFT,fill=BOTH,expa
nd=True)
b4=Button(bottomframe,text="black",bg="black",fg="white").pack(fill=BOTH,expand=Tru
e)
mainloop()
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 118
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 119
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
74. Aim:Design the following GUI using Grid geometry Manager

Program:
from tkinter import *
win=Tk()
l=Label(win,text="Find:").place(x=10,y=10)
l=Label(win,text="Replace:").place(x=10,y=40)
e=Entry(win,width=60).place(x=60,y=10)
e=Entry(win,width=60).place(x=60,y=40)
b=Button(win,text="Find",width=10).place(x=450,y=10)
b=Button(win,text="FindAll",width=10).place(x=450,y=40)
b=Button(win,text="Replace",width=10).place(x=450,y=70)
b=Button(win,text="ReplaceAll",width=10).place(x=450,y=100)
c=Checkbutton(win,text="Match whole word only").place(x=10,y=70)
c=Checkbutton(win,text="Match Case").place(x=10,y=100)
c=Checkbutton(win,text="Wrap around").place(x=10,y=130)
l=Label(win,text="Directions:").place(x=200,y=70)
c=Radiobutton(win,text="up").place(x=200,y=100)
c=Radiobutton(win,text="down").place(x=280,y=100)
mainloop()
Save:- “74.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 120
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
75. Aim:Design the following GUI using Grid geometry Manager

Program:
import tkinter as tk
obj=tk.Tk()
obj.title("grid layout")
a=[]
for m in range(0,36):
n=str(m+1)
a.append(n)
k=0
for i in range(0,6):
for j in range(0,6):
b1=tk.Button(obj,text=a[k])
b1.grid(row=i,column=j)
k+=1
obj.mainloop()
Save:- “74.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 121
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
76. Aim: Design the following GUI using Place geometry Manager
A. B.

Program:
76A.py
from tkinter import *
win=Tk()
b=Button(win,text="Absolute Placement").place(x=50,y=100)
b1=Button(win,text="Relative").place(x=70,y=120)
win.mainloop()

76B.py
from tkinter import *
root=Tk()
root.title("Geometry Manager place Example")
root.geometry("500x500")

btn_height=Button(root,text="50px high")
btn_height.place(height=50,x=200,y=200)

btn_width=Button(root,text="60px wide")
btn_width.place(width=60,x=300,y=300)

btn_relheight=Button(root,text="Relheight of 0.6")

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 122
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
btn_relheight.place(relheight=0.6)

btn_relwidth=Button(root,text="Relwidth of 0.2")
btn_relwidth.place(relwidth=0.2)

btn_relx=Button(root,text="Relx of 0.3")
btn_relx.place(relx=0.3)

btn_rely=Button(root,text="Rely of 0.7")
btn_rely.place(rely=0.7)

btn_x=Button(root,text="X=400px")
btn_x.place(x=400)

btn_y=Button(root,text="Y=321")
btn_y.place(y=321)
root.mainloop()
Save:- “76.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 123
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
77. Aim:Write a python program that display message in a message box when click on
a red button.

Program:
from tkinter import *
from tkinter import messagebox
w=Tk()
def fun():
messagebox.showinfo("hello","red button clicked")
b=Button(w,text="Green").pack(side=TOP,ipady=3,ipadx=2)
b=Button(w,text="Red",command=fun,activebackground="pink",activeforeground="red").p
ack(side=LEFT,ipady=3,ipadx=2)
b=Button(w,text="Blue").pack(side=RIGHT,ipady=3,ipadx=2)
b=Button(w,text="Yellow").pack(side=BOTTOM,ipady=3,ipadx=2)
mainloop()
Save:- “77.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 124
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
78. Aim:Write a python program with a canvas widget that displays various
geometrical shapes.

Program:
from tkinter import *
top=Tk()
top.title("Canvas Example")
#top.geometry("1000x800")
c=Canvas(top,bg="yellow",height="500",width=500)
arc=c.create_arc((5,10,100,150),start=0,extent=150,fill="red")
oval=c.create_oval((220,100,400,10),fill="blue")
poly=c.create_polygon((150,200,100,200,150,70),fill="green")
line=c.create_line((300,200,200,200),fill="black")
c.pack()
top.mainloop()
Save:- “78.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

79. Aim:Write a python program that accepts two numbers from the entry widget and
display their sum, difference, multiplication, division and remainder in result entry box
when clicking on corresponding buttons.
Program:

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 125
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
from tkinter import *
root = Tk()
def res_add():
add=int(entry1.get())+int(entry2.get())
entry3.delete(0,END)
entry3.insert(0,add)
def res_sub():
add=int(entry1.get())-int(entry2.get())
entry3.delete(0,END)
entry3.insert(0,add)
def res_mul():
add=int(entry1.get())*int(entry2.get())
entry3.delete(0,END)
entry3.insert(0,add)
def res_div():
add=int(entry1.get())/int(entry2.get())
entry3.delete(0,END)
entry3.insert(0,add)
number1=StringVar()
number2=StringVar()
label1=Label(root,text="Enter First Number").grid(row=0,column=0)
entry1=Entry(root,textvariable=number1,width=50)
entry1.grid(row=0,column=1,columnspan=4)
label2=Label(root,text="Enter second Number").grid(row=1,column=0)
entry2=Entry(root,textvariable=number2,width=50)
entry2.grid(row=1,column=1,columnspan=4)
label3=Label(root,text="Result").grid(row=2,column=0)
entry3=Entry(root,width=50)
entry3.grid(row=2,column=1,columnspan=4)
buttons1=Button(root,text="Add",command=res_add).grid(row=3,column=0,ipadx=40,ipady
=10)
buttons2=Button(root,text="Subtract",command=res_sub).grid(row=3,column=1,ipadx=40,i
pady=10)
buttons3=Button(root,text="Muliplication",command=res_mul).grid(row=3,column=2,ipadx
=20,ipady=10)
buttons4=Button(root,text="Division",command=res_div).grid(row=3,column=3,ipadx=20,i
pady=10)
root.mainloop()

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 126
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Save:- “74.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 127
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
80. Aim:Write a python program with checkbutton widget that asks the programmer
to select the programming languages he knows and a button which when clicked
displays the languages known to the programmer in the messagebox widget.
Program:
from tkinter import *
master = Tk()
def var_states():
top= Toplevel(master)
top.geometry("750x250")
top.title("Child Window")
if var1.get():
Label(top, text= "You know Python", font=('Calibri 18 bold')).grid(row=0, column=0,
sticky=W)
if var2.get():
Label(top, text= "You know Java", font=('Calibri 18 bold')).grid(row=1, column=0,
sticky=W)
if var3.get():
Label(top, text= "You know C++", font=('Calibri 18 bold')).grid(row=2, column=0,
sticky=W)
master.geometry("500x500")
Label(master, text="Your Programming language:").grid(row=0, column=0, sticky=W)
var1 = IntVar()
Checkbutton(master, text="Python", variable=var1).grid(row=1, column=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text="Java", variable=var2).grid(row=2, column=0, sticky=W)
var3 = IntVar()
Checkbutton(master, text="C++", variable=var3).grid(row=3, column=0, sticky=W)
Button(master, text='Button', command=var_states).grid(row=4, sticky=W, pady=4)
mainloop()
Save:- “80.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 128
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 129
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
81. Aim: Write a python program with radiobutton widget that asks the user to select
his gender and a button which when clicked display his gender in the messagebox
widget.
Program:
from tkinter import *
from tkinter import messagebox
win=Tk()
def fm():
messagebox.showinfo("Gender", "Female")
def m():
messagebox.showinfo("Gender", "Male")
var=IntVar()
b=Radiobutton(win,text="Female",command=fm,value=1).pack()
b1=Radiobutton(win,text="Male",command=m,value=2).pack()
mainloop()
Save:- “81.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 130
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
82. Aim:Write a python program with frame widget like below.

Program:
from tkinter import *
top=Tk()
top.geometry("140x100")
frame=Frame(top)
frame.pack()
leftframe=Frame(top)
leftframe.pack(side=LEFT)
rightframe=Frame(top)
rightframe.pack(side=RIGHT)
btn1=Button(frame,text='submit',fg='red',activebackground='yellow')
btn1.pack(side=LEFT)
btn2=Button(frame,text='remove',fg='brown',activebackground='yellow')
btn2.pack(side=RIGHT)
btn3=Button(rightframe,text='add',fg='blue',activebackground='blue')
btn3.pack(side=LEFT)
btn4=Button(leftframe,text='modify',fg='pink',activebackground='pink')
btn4.pack(side=RIGHT)
top.mainloop()
Save:- “82.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 131
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 132
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
83. Aim:Write a python program with LabelFrame widget like below.

Program:
from tkinter import *
top=Tk()
top.title("label frame widget example")
labelframe1=LabelFrame(top,text="positive comments")
labelframe1.pack(fill="both",expand="yes")
toplabel=Label(labelframe1,text="place to put the positive comments")
toplabel.pack()
labelframe2=LabelFrame(top,text="negative comments")
labelframe2.pack(fill="both",expand="yes")
bottomlabel=Label(labelframe2,text="place to put the negative comments")
bottomlabel.pack()
top.mainloop()
Save:- “83.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

84. Aim:Write a python program with Listbox widget.


Program:
from tkinter import *
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 133
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
top = Tk()
listbox = Listbox(top, height = 10,width = 15,bg = "grey",activestyle = 'dotbox',font =
"Helvetica",fg = "yellow")
top.geometry("300x250")
label = Label(top, text = " FOOD ITEMS")
listbox.insert(1, "Nachos")
listbox.insert(2, "Sandwich")
listbox.insert(3, "Burger")
listbox.insert(4, "Pizza")
listbox.insert(5, "Burrito")
label.pack()
listbox.pack()
top.mainloop()
Save:- “84.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

85. Aim:Write a python program to create a window with a menu bar and sub menu
items using Menu widget.
Program:
from tkinter import Toplevel, Button, Tk, Menu
top = Tk()

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 134
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
top.config(menu=menubar)
top.mainloop()
Save:- “85.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 135
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 136
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
86. Aim:Write a python program with Message widget.
Program:
from tkinter import *
top=Tk()
top.title("message widget example")
var=StringVar()
msg=Message(top,text="welcome to message widget")
msg.pack()
top.mainloop()
Save:- “86.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 137
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
87. Aim:Write a python program with OptionMenu widget.
Program:
from tkinter import *
master=Tk()
master.title("option menu widget")
var=StringVar(master)
var.set("one")
option=OptionMenu(master,var,"one","two","three","four")
option.pack()
def ok():
print("value is",var.get())
master.quit()
button=Button(master ,text="ok",command=ok)
button.pack()
mainloop()
Save:- “87.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

88. Aim:Write a python program with PanedWindow widget.


Program:
from tkinter import *
def add():

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 138
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
a=int(e1.get())
b=int(e2.get())
leftdata=str(a+b)
left.insert(1,leftdata)
w1=PanedWindow()
w1.pack(fill=BOTH,expand=1)
left=Entry(w1,bd=5)
w1.add(left)
w2=PanedWindow(w1,orient=VERTICAL)
w1.add(w2)
e1=Entry(w2)
e2=Entry(w2)
w2.add(e1)
w2.add(e2)
bottom=Button(w2,text="add",command=add)
w2.add(bottom)
mainloop()
Save:- “88.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 139
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
89. Aim:Write a python program with Scale widget.
Program:
from tkinter import *
def select():
sel="value="+str(v.get())
label.config(text=sel)
top=Tk()
top.title("scale widget example")
#top.geometry("200*200")
v=DoubleVar()
scale=Scale(top,variable=v,from_=1,to=50,orient=HORIZONTAL)
scale.pack(anchor=CENTER)
btn=Button(top,text="value",command=select)
btn.pack(anchor=CENTER)
label=Label(top)
label.pack()
top.mainloop()
Save:- “89.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 140
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
90. Aim:Write a python program with Scrollbar widget.
Program:
from tkinter import *
top=Tk()
top.title("scrollbar widget example")
sb=Scrollbar(top)
sb.pack(side=RIGHT,fill=Y)
mylist=Listbox(top,yscrollcommand=sb.set)
for line in range(30):
mylist.insert(END,"number"+str(line))
mylist.pack(side=LEFT)
sb.config(command=mylist.yview)
mainloop()
Save:- “90.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 141
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
91. Aim:Write a python program with Spinbox widget.
Program:
from tkinter import *
top=Tk()
top.title("spinbox widget example")
spin=Spinbox(top,from_=0,to=25)
spin.pack()
top.mainloop()
Save:- “91.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 142
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
92. Aim:Write a python program with Text widget.
Program:
from tkinter import *
top=Tk()
top.title=("text widget example")
text=Text(top)
text.insert(INSERT,"Name.....")
text.insert(END,"salary..")
text.pack()
text.tag_add("write here","1.0","1.4")
text.tag_add("click here","1.8","1.13")
text.tag_config("write here",background="yellow",foreground="black")
text.tag_config("click here",background="black",foreground="white")
top.mainloop()
Save:- “92.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 143
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
93. Aim:Write a python program with Toplevel widget.
Program:
from tkinter import *
root=Tk()
root.title("top level example")
#root.geometry("200*200")
def open():
top=Toplevel(root)
top.mainloop()
btn=Button(root,text="open",command=open)
btn.place(x=75,y=50)
root.mainloop()
Save:- “93.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 144
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
94. Aim:Write a python program to handle mouse events.
Program:
from tkinter import *
var = Tk()
def leftclick(event):
print("left")
def middleclick(event):
print("middle")
def rightclick(event):
print("right")
frame = Frame(var, width=300, height=250)
frame.bind("<Button-1>", leftclick)
frame.bind("<Button-2>", middleclick)
frame.bind("<Button-3>", rightclick)
frame.pack()
var.mainloop()
Save:- “94.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 145
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
95. Aim:Write a python program to handle key board events.
Program:
from tkinter import *
from tkinter import messagebox
def myfunction(event):
print("Key is Pressed",event.char)
emptylabel.config(text=event.char+"is Pressed")
if event.char=='a':
messagebox.showinfo('Key Event',event.char+'is Pressed')
window=Tk()
window.title('Key Event Demo')
window.geometry('500x400')
window.bind('<Key>',myfunction)
Label(window,text='Press any Key',fg='black',font=('Arial',40)).pack(pady=20)
emptylabel=Label(window,fg='blue',bg='white',font=('Arial',30))
emptylabel.pack()
window.mainloop()
Save:- “95.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 146
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
96. Aim:Write a python program with a regular expression to validate a phone
number. A phone number of DDD-DDDD-DDD form where D stands for a digit.
Program:
import re
pattern="(0/91)?[7-9][0-9]{9}"
mobile=input("enter your phone number:")
result=re.findall(pattern,mobile)
if(result):
print("valid phone number is :",mobile)
else:
print("please enter a valid phone number")
Save:- “96.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 147
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
97. Aim:A. Write a python program that finds all the occurrences of a string of a
particular pattern in a file using findall() function in remodule.
B. Write a python program that finds and replaces all the occurrences of a string of a
particular pattern with another string using sub() function in re module.
C. Write a python program that splits the string at every occurrence of the sub-string
and returns a list of strings which have been split using split() function in re module.
D. Write a python program to search for a character or sub-string using search() and
match() functions in re module.
Program:
97A.py
import re as r
print(r.findall(input("enter pattern to find it's occurances :"),open("sample.txt",'r').readline()))

#sample.txt file:
#hello good morning!! hello good morning!! hello good morning!! hello good morning!!

97B.py
import re
pattern = re.compile(r'(Cats|Dogs)')
string_a = pattern.sub("Pets", "Dogs are a man's best friend.")
string_b = pattern.sub("Animals", "Cats enjoy sleeping.")
print(string_a)
print(string_b)

97C.py
import re
str="welcome to Regular Expression Module!"
sub="\s"
l=re.split(sub,str)
print(l)

97D.py
import re
name="Hello pk bhai!"
print(re.search("Hello",name,))#search the entire string
print(re.match("pk",name))#search from the beginning or else returns None
print(re.search("HELLO",name,re.IGNORECASE))
print(re.search("HELoO",name,re.IGNORECASE))
print(re.match("Hello pk",name))

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 148
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 149
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
98. Aim:Write a python program that validates the email id.
Program:
import re
# Make a regular expression
# for validating an Email
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
# Define a function for
# for validating an Email
def check(email):
if(re.fullmatch(regex, email)):
print("Valid Email")
else:
print("Invalid Email")
email = "ankitrai326@gmail.com"
check(email)
email = "my.ownsite@our-earth.org"
check(email)
email = "ankitrai326.com"
check(email)
Save:- “98.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 150
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
99. Aim:Write a python program that validates the IP address.
Program:
import re
regex='''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'''
def check(Ip):
if(re.search(regex,Ip)):
print("valid IP address")
else:
print("invalid IP address")
if __name__=='__main__':
Ip="192.168.0.1"
check(Ip)
Ip="366.1.2.2"
check(Ip)
Save:- “99.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 151
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
100. Aim: Write a python program that validates your PIN number.
Program:
import re
#PIN Validation using RegEx (regular Expressions)
pin_patt="[0-9]+-[a-zA-z]+-[0-9]"
pin=input("Enter you PIN: ")
if re.search(pin_patt,pin):
print("Valid input")
else:
print("Invalid Input")
Save:- “100.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 152
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
101. Aim: Write a python program to show various ways to read and write data in a
file
Program:
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt", "r+")
print("Output of Read function is ")
print(file1.read())
print()

# seek(n) takes the file handle to the nthbite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)

# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Save:- “101.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 153
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 154
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
102. Aim: Write a python program to copy one file into another.
Program:
with open('myfile.txt','r') as file1, open('myfile2.txt','w') as file2:
for line in file1:
file2.write(line)
Save:- “102.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 155
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
103. Aim: Write a python program to count the number of lines, number of words and
the number of characters in the file.
Program:
import os
def counter(fname):
num_words = 0
num_lines = 0
num_charc = 0
num_spaces = 0
# after completion of work
with open(fname, 'r') as f:
for line in f:
line = line.strip(os.linesep)
wordslist = line.split()
num_lines = num_lines + 1
num_words = num_words + len(wordslist)
num_charc = num_charc + sum(1 for c in line
if c not in (os.linesep, ' '))
num_spaces = num_spaces + sum(1 for s in line
if s in (os.linesep, ' '))
print("Number of words in text file: ", num_words)
print("Number of lines in text file: ", num_lines)
print("Number of characters in text file: ", num_charc)
print("Number of spaces in text file: ", num_spaces)
# Driver Code:
if __name__ == '__main__':
fname = 'myfile.txt'
try:
counter(fname)
except:
print('File not found')

Save:- “103.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 156
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 157
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
104. Aim: Write a python program that appends all the contents of one file at the end
of another file.
Program:

firstfile = input("Enter the name of first file ")


secondfile = input("Enter the name of second file ")

f1 = open(firstfile, 'r')
f2 = open(secondfile, 'r')

print('content of first file before appending -', f1.read())


print('content of second file before appending -', f2.read())

f1.close()
f2.close()

f1 = open(firstfile, 'a+')
f2 = open(secondfile, 'r')

f1.write(f2.read())

f1.seek(0)
f2.seek(0)

print('content of first file after appending -', f1.read())


print('content of second file after appending -', f2.read())

f1.close()
f2.close()

Save:- “104.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 158
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 159
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
105. Aim: Write a python program to rename and delete a single file.
Program:
Import os
os.rename("C:\Users\DELL\Desktop\test1.txt","C:\Users\DELL\Desktop\test100.txt")
Save:- “105.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 160
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
106. Aim: Write a python program to remove an empty folder and folder that contains
files or sub folders.
Program:
# Python program to demonstrate
# shutil.rmtree()
import shutil
import os
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
# directory
dir = "Authors"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)
Save:- “106.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Before:

After:

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 161
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
107. Aim: Write a python program that performs CRUD operations on a student
table(name,pin,age) with a primary key.
Program:
import mysql.connector as ms
con = ms.connect(host = "localhost", user = "root",passwd =
"chinni",database="sample",port=4040)
mycursor=con.cursor();
print("CRUD-create,read,update,delete")
print("Creating Operation......")
mycursor.execute("CREATE TABLE student(name VARCHAR(30),pin VARCHAR(20)
NOT NULL PRIMARY KEY,age INT(2))")
print("Table student created successfully...")
con.commit()
mycursor.execute("desc student")
struct=mycursor.fetchall()
for i in struct:
print(i)
con.commit()
sql="INSERT INTO student(name,pin,age) VALUES(%s,%s,%s)"
val=[("Divya Bharathi","19001-cm-213",18),
("Gopichand","19001-cm-212",19),
("Poojitha","19001-cm-244",19)]
mycursor.executemany(sql,val)
con.commit()
print(mycursor.rowcount," records inserted ")
print("Reading Operation.....")
mycursor.execute("SELECT * FROM student")
data=mycursor.fetchall()
for i in data:
print(i)
con.commit()
print("Updating operation.....")
sql="UPDATE student SET age=%s WHERE name=%s"
val=(17,"Divya Bharathi")
mycursor.execute(sql,val)
print(mycursor.rowcount," records affected ")
con.commit()
print("Delete Operation......")
STUDENT NAME:B.RAJESH PIN:19001-CM-221
FACULTY: M. SURESHM.Tech 162
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
mycursor.execute("DELETE FROM student WHERE name='Gopichand'")
print(mycursor.rowcount," records affected ")
Save:- “107.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-

CRUD-create,read,update,delete
Creating Operation......
Table student created successfully...
('name', 'varchar(30)', 'YES', '', None, '')
('pin', 'varchar(20)', 'NO', 'PRI', None, '')
('age', 'int(2)', 'YES', '', None, '')
3 records inserted
Reading Operation.....
('Gopichand', '19001-cm-212', 19)
('Divya Bharathi', '19001-cm-213', 18)
('Poojitha', '19001-cm-244', 19)
Updating operation.....
1 records affected
Delete Operation......
1 records affected

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 163
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
108. Aim: Write a python program that executes stored procedures.
Program:
Procedure in sample database:
delimiter #
mysql> create procedure emp(IN name char(30),In id int,Insal float)
-> begin
-> insert into employee values(name,id,sal);
-> end;
-> #
import mysql.connector as ms
con=ms.connect(host="localhost",user="root",password="Vinay239",database="sample")
cur=con.cursor()
cur.execute("call emp('Divya',213,450.50);")
con.commit()
print(cur.rowcount,"record inserted ")
con.close()

Save:- “108.py”
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
1 record inserted

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 164
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
109. Aim: Write a python program that stores images and files in a table.
Program:
import mysql.connector
import os
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData
def insertBLOB(emp_id, name, photo, biodataFile):
print("Inserting BLOB into python_employee table")
try:
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='root',
password='Vinay239')
cursor = connection.cursor()
sql_insert_blob_query = """ INSERT INTO python_employee
(id, name, photo, biodata) VALUES (%s,%s,%s,%s)"""
empPicture = convertToBinaryData(photo)
file = convertToBinaryData(biodataFile)
# Convert data into tuple format
insert_blob_tuple = (emp_id, name, empPicture, file)
result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
connection.commit()
print("Image and file inserted successfully as a BLOB into python_employee table", result)
except mysql.connector.Error as error:
print("Failed inserting BLOB data into MySQL table {}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
insertBLOB(1, "vinay","pythonimg1.png","vianybio.txt")
insertBLOB(2, "somesh", "pythonimg2.png","someshbio.txt")

Save:- “109.py”

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 165
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
Run:- F5 in IDLE or Alt+shift+F10 in Pycharm
Output:-
Inserting BLOB into python_employee table
Image and file inserted successfully as a BLOB intopython_employee table
None
MySQL connection is closed
Inserting BLOB into python_employee table
Image and file inserted successfully as a BLOB into python_employee table
None
MySQL connection is closed

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 166
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
110. Aim: Write the steps to enable I2C and SPI interface in Raspbian Operating
system PI board using the command prompt and GUI.
Program:
Method I:
A. Steps to enable SPI interface in Raspbian OS PI board using Command prompt:
 Firstly, open TERMINAL
 Then, run sudoraspi-config
 Now use the down arrow to select Interfacing options
 Arrow down and select P4 SPI.
 Select yes when it asks you to enable SPI,
 Then select yes if it asks about automatically loading the kernel module.
 Now select Finish button.
 Finally, select yes to reboot to apply the changes.

B. Steps to enable I2C interface in Raspbian OS PI board using Command prompt:


 Firstly, open TERMINAL
 Then, run sudoraspi-config
 Now use the down arrow to select Interfacing Options
 Arrow down and select IP 512C.
 Select yes when it asks you to enable 12C.
 Also select yes if it asks about automatically loading the kernel module.
 Now select Finish button.
 Finally, select yes to reboot to apply the changes.

Method II:
A. Steps to enable I2C interface in Raspbian OS PI board using GUI:
 Firstly go to the Start Menu then, select Preferences and then select and open Raspberry
Pi Configuration.
Menu>Preferences>RaspberryPiConfiguration.
 Now a popup Raspberry Pi Configuration Window will appear
 Then go to Interfacing tab and select Enable for 12C.
 Click on the OK button to save.
 Now it’s time to restart the Raspberry Pi to apply changes.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 167
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
B. Steps to enable SPI interface in Raspbian OS PI board using GUI:
 Firstly go to the Start Menu then, select Preferences and then select and open Raspberry
Pi Configuration.
Menu>Preferences>RaspberryPiConfiguration.
 Now a popup Raspberry Pi Configuration Window will appear
 Then go to Interfacing tab and select Enable for SPI.
 Click on the OK button to save.
 Now it’s time to restart the Raspberry Pi to apply changes.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 168
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
111. Aim: Write the steps to configure the circuit and python program to turn on and
turn off LED.
Program:
Building the Circuit:
 Take a Bread board and place the LED and the Resistor on it.
 Connect the positive terminal of the LED to the PIN11 on GPIO and connect the
other Negative terminal of the LED to the ground on GPIO using jumper wire.
 Now create a LED.py file in IDLE editor and write down the following program
andsave it.
 Now run the program to turn on and turn off LED.

Program using Method-I:


import RPi.GPIO as GPIO ##Import GPIO library
import time
GPIO.setmode(GPIO.BCM)##Use board pin numbering
GPIO.setwarnings(False)
GPIO.setup(11,GPIO.OUT)##Setup GPIO Pin11 to OUT
while True:
print("LEDon")
GPIO.output(11,GPIO.HIGH)##Turn on Led
time.sleep(1)##Wait for one second
print("LEDoff")
GPIO.output(11,GPIO.LOW)##Turn off Led
time.sleep(1)##Wait for one second
GPIO.cleanup()

 Install the gpio zero module using following command.


sudo apt install python3-gpiozero

Program using Method-II:

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 169
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
#This is Led Blinking Program
from gpiozero import LED
from time import sleep
led=LED(11)#define GPIO11 pin as LED
while True:
led.on()#LEDON
sleep(0.5)#0.5sdelay
led.off()#LED0FF
sleep(0.5)#0.5sdelay
GPIO.cleanup()

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 170
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
112.Aim:Write the steps to configure the circuit and python program to make a buzzer
playing sound using the buzzer.
Procedure:
Building the Circuit:
 Take a Bread board and place the Buzzer on it.
 Now connect the Negative terminal of the buzzer to the Raspberry Pi’s GND pin in
the same row bread board using jumper wire.
 Then, connect the Positive terminal of the buzzer to the Raspberry Pi’s GPIO Pin
23 pin in the same row bread board using jumper wire.
 Now create a Buzzer.py file in IDLE editor and write down the following program
and save it.
 Now run the program to make a buzzer playing sound.

Program using Method-I:


#Libraries
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)#Disable warnings(optional)
GPIO.setmode(GPIO.BCM)#Select GPIO mode
GPIO.setup(23,GPIO.OUT)#Set buzzer-pin23 as output
while True:
GPIO.output(23,GPIO.HIGH)
print("Beep")
sleep(1)#Delayinseconds
GPIO.output(23,GPIO.LOW)
print("NoBeep")
sleep(1)

 Now install the gpio zero module using following command.

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 171
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
sudo apt install python3-gpiozero

Program using Method-II:


#This is Buzzer Program
from gpiozero import Buzzer
from time import sleep
buzzer=Buzzer(23)#Define GPIO23 as buzzer
while True:
buzzer.on()#Buzzer ON
sleep(0.5)#0.5s delay
buzzer.off()#Buzzer OFF
sleep(0.5)#0.5sdelay

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 172
SUBJECT TITLE:PYTHON PROGRAMMING LAB PRACTICE BRANCH:DCME
SUBJECT CODE:18CM-508P(A) SEM:5 SHIFT:2
113. Aim: Write the steps to connect the Raspberry PI board to the internet using
WIFI network.
Procedure:
Steps to connect the Raspberry PI board to the internet using WIFI network:
 First, to turn on the WiFi Adapter, click on the up–down arrow in top right corner of the
Raspbian OS desktop.
 Click on the double arrow symbol once again to see the list of WiFi networks
availableneartheRaspberryPi.SelecttheWiFinetworkfromthelist.
 YouwillnowbeaskedtoenterthePreSharedKeyofthenetwork.Thisisnothing
butthepasswordoftheWiFiconnection.
 EnterthepasswordandclickonOK.
YoucanseethattheRaspberryPiisconnectedtoWiFinetworkofchoiceandis
highlightedwithagreencheckmark

STUDENT NAME:B.RAJESH PIN:19001-CM-221


FACULTY: M. SURESHM.Tech 173

You might also like