Python Practical
Python Practical
Division/Batch :- E/E1
150200107065 Page 1
4. Create a program that asks the user for a number 12 22/12/2020
and then prints out a list of all the divisors of that
number. (If you don’t know what a divisor is, it is a
number that divides evenly into another number.
For example, 13 is a divisor of 26 because 26 / 13
has no remainder.) [CO-1]
5. Factors. Write a function called getfactors() that 13 22/12/2020
takes a single integer as an argument and returns a
list of all its factors, including 1 and itself. [CO-1]
6. Take two lists, say for example these two: 14 to 22/12/2020
15
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
7. Ask the user for a string and print out whether this 16 to 29/12/2020
string is a palindrome or not. Write this program 17
with and without loops(A palindrome is a string
that reads the same forwards and backwards.) [CO-
1]
8. Determine if two strings match (without using 18 to 29/12/2020
comparison operators or the cmp() built-in 19
function) by scanning each string. Extra credit:
Add caseinsensitivity to your solution. [CO-4]
9. Write a Python program that counts the number of 20 29/12/2020
occurrences of the character in the given string.
Provide two implementations: recursive and
iterative. [CO-4]
10. Use random library to generate list a and Write one 21 5/1/2021
line of Python that takes this list a and makes a new
list that has only the even elements of this list in it.
[CO-4]
11. Generate a random number between 1 and 9 22 to 5/1/2021
(including 1 and 9). Ask the user to guess the 23
number, then tell them whether they guessed too
low, too high, or exactly right also perform
following task [CO-1]
150200107065 Page 2
12. Ask the user for a number and determine whether 24 to 5/1/2021
the number is prime or not using function/without 25
function /list comprehensions. [CO-1]
13. Write a program that takes a list of numbers (for 26 12/1/2021
example, a = [5, 10, 15, 20, 25]) and makes a new
list of only the first and last elements of the given
list. For practice, write this code inside a function.
[CO-1]
14. Write a program that asks the user how many 27 to 12/1/2021
Fibonacci numbers to generate and then generates 28
them. Take this opportunity to think about how you
can use functions. Make sure to ask the user to
enter the number of numbers in the sequence to
generate.(Hint: The Fibonacci seqence is a
sequence of numbers where the next number in the
sequence is the sum of the previous two numbers in
the sequence. The sequence looks like this: 1, 1, 2,
3, 5, 8, 13, …) [CO-1]
15. Write a program (function!) that takes a list and 29 12/1/2021
returns a new list that contains all the elements of
the first list minus all the duplicates. Write two
different functions to do this - one using a loop and
constructing a list, and another using sets. [CO-1]
16. Create a class student with following member 30 to 19/1/2021
attributes: roll no, name, age and total marks. 31
Create suitable methods for reading and printing
member variables. Write a python program to
overload ‘==’ operator to print the details of
students having same marks. [CO-2]
17. Create a class Employee with data members: name, 32 19/1/2021
department and salary. Create suitable methods for
reading and printing employee information. [CO-2]
18. Define a class Complex which represents the 33 to 19/1/2021
complex number. And overload + operator which 34
add two complex objects. [CO-2]
19. Implement binary search algorithm to seach name 35 to 2/2/2021
for the given list of names. [CO-4][CO-1] 36
150200107065 Page 3
23. Implement Hashtable with its various functionality. 41 to 9/2/2021
[CO-1][CO-4] 42
150200107065 Page 4
34. Create following regular polygons (regular means 64 to 20/04/2021
all sides the same lengths, all angles the same) 65
using for loop in turtle [CO-4]
• An equilateral triangle
• A square
• A hexagon
• An octagon.
150200107065 Page 5
Que.1) Create a program that asks the user to enter their name and their age. Print out
a message addressed to them that tells them the year that they will turn 100 years old.
Program : Practical_1.py
import datetime
currentYear = datetime.datetime.now();
OUTPUT :
150200107065 Page 6
Que.2) Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user
2. Ask the user for two numbers: one number to check (call it num) and one
number to divide by (check). If check divides evenly into num, tell that to the
Program : Practical_2.py
1.
if number % 4 == 0:
elif number % 2 == 0:
else:
2.
150200107065 Page 7
if num % check == 0:
else:
OUTPUT :
150200107065 Page 8
Que.3) Take a list, say for example this one:
and write a program that prints out all the elements of the list that are less than 5
1. Instead of printing the elements one by one, make a new list that has all the
elements less than 5 from this list in it and print out this new list.
3. Ask the user for a number and return a list that contains only elements from the
original list that are smaller than that number given by the user.
Program: Practical_3.py
1.
userData = []
while True:
if(str(data).upper() == "Q"):
break
else:
userData.append(int(data))
output = ""
150200107065 Page 9
for data in userData:
if data < 5:
newList = []
if data < 5:
newList.append(data)
2.
3.
newOutput = ""
150200107065 Page 10
print('\nList which has all number less than {} : {}'.format(userInput,newOutput)) #
Filtered List
OUTPUT:
150200107065 Page 11
Que.4) Create a program that asks the user for a number and then prints out a list of all
the divisors of that number. (If you don’t know what a divisor is, it is a number that
divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13
has no remainder.)
Program: Practical_4.py
listRange = list(range(1,number+1))
divisorList = []
if number % value == 0:
divisorList.append(value)
print('\nAnswer : {}'.format(divisorList))
OUTPUT:
150200107065 Page 12
Que.5) Factors. Write a function called getfactors() that takes a single integer as an
argument and returns a list of all its factors, including 1 and itself.
Program : Practical_5.py
def getfactors(number):
print('\nAnswer : {}'.format(getfactors(number)))
OUTPUT :
150200107065 Page 13
Que.6) Take two lists, say for example these two:
and write a program that returns a list that contains only the elements that are common
between the lists (without duplicates). Make sure your program works on two lists of
different sizes.
Program: Practical_6.py
inputA = []
inputB = []
result = []
while True:
if(data.upper() == 'Q'):
break
else:
inputA.append(int(data))
while True:
150200107065 Page 14
if(data.upper() == 'Q'):
break
else:
inputB.append(int(data))
result = list(set(result))
print('\nAnswer : {}'.format(result))
OUTPUT :
150200107065 Page 15
Que.7) Ask the user for a string and print out whether this string is a palindrome or
not.
Write this program with and without loops(A palindrome is a string that reads the
same forwards and backwards.)
Program: Practical_7.py
150200107065 Page 16
1. Without Loop
reverseWord=word[::-1]
if word == reverseWord:
else:
2. With Loop
def reverse(word):
x = ''
for i in range(len(word)):
x += word[len(word)-1-i]
return x
x = reverse(word)
if word == x:
else:
OUTPUT:
150200107065 Page 17
Que.8) Determine if two strings match (without using comparison operators or the cm
p() built-in function) by scanning each string. Extra credit: Add case in sensitivity to
your solution.
150200107065 Page 18
Program: Practical_8.py
def checkString(str1,str2):
counter = 0
if(len(str1) == len(str2)):
if ord(character) - ord(str2[counter]) == 0:
counter += 1
else:
return False
else:
return False
if counter == len(str1):
return True
if(checkString(string1,string2)):
else:
OUTPUT:
150200107065 Page 19
150200107065 Page 20
Que.9) Write a Python program that counts the number of occurrences of the character
in the given string. Provide two implementations: recursive and iterative.
Program: Practical_9.py
import json
OUTPUT:
150200107065 Page 21
Que.10) Use random library to generate list a and Write one line of Python that takes
this list a and makes a new list that has only the even elements of this list in it.
Program: Practical_10.py
import random
MAX_VALUE = 1000
oldList = []
oldList.append(random.randint(0,MAX_VALUE))
oldList.sort()
newList.sort()
OUTPUT:
150200107065 Page 22
Que.11) Generate a random number between 1 and 9 (including 1 and 9). Ask the user
to guess the number, then tell them whether they guessed too low, too high, or exactly
right also perform following task
• Keep track of how many guesses the user has taken, and when the game ends, print
this out.
Program: Practical_11.py
import random
def evaluateNumber(number,correctNumber,numberOfTry):
return False
return False
else:
print(correctNumber)
return True
correctNumber = random.randint(1,9)
numberOfTry = 0
print('\nGuess the number between 1 to 9 and type exit to quit the game')
while True:
if(number == 'exit'):
150200107065 Page 23
print('\nYou lose the game in {} try & Answer was :
{}'.format(numberOfTry,correctNumber))
break
else:
numberOfTry += 1
if(evaluateNumber(int(number),correctNumber,numberOfTry)):
break
OUTPUT:
150200107065 Page 24
Que.12) Ask the user for a number and determine whether the number is prime or not
using function/without function /list comprehensions.
Program: Practical_12.py
# Using Function
def isPrime(num):
print('\nUsing Function')
flag = False
if num > 1:
if (num % i) == 0:
flag = True
break
return flag
def printMessage(number,result):
if result:
else:
modNumber = abs(number);
type = 3
if(type == 1):
printMessage(number,isPrime(modNumber))
elif type == 2 :
print('\nWithout Function')
150200107065 Page 25
flag = False
if modNumber > 1:
if modNumber % index == 0:
flag = True
break
printMessage(number,flag)
else:
print('\nList Comprehensions')
if len(primes) == 0 :
printMessage(number,False)
else:
printMessage(number,True)
OUTPUT:
150200107065 Page 26
Que.13) Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20,
25]) and makes a new list of only the first and last elements of the given list. For
practice, write this code inside a function.
Program: Practical_13.py
def list_ends(a_list):
lst1 = []
OUTPUT:
150200107065 Page 27
Que.14) Write a program that asks the user how many Fibonacci numbers to generate
and then generates them. Take this opportunity to think about how you can use
functions. Make sure to ask the user to enter the number of numbers in the sequence to
generate.(Hint: The Fibonacci sequence is a sequence of numbers where the next
number in the sequence is the sum of the previous two numbers in the sequence. The
sequence looks like this: 1, 1, 2, 3, 5, 8, 13, ...)
Program: Practical_14.py
def gen_fib():
count = int(input('\nHow Many Fibonacci numbers would you like to Generate? : '))
i=1
if count == 0:
fib = []
elif count == 1:
fib = [1]
elif count == 2:
fib = [1,1]
fib = [1,1]
fib.append(fib[i] + fib[i-1])
i += 1
return fib
print('\nAnswer : ',gen_fib())
OUTPUT:
150200107065 Page 28
150200107065 Page 29
Que.15) Write a program (function!) that takes a list and returns a new list that
contains all the elements of the first list minus all the duplicates. Write two different
functions to do this - one using a loop and constructing a list, and another using sets.
Program: Practical_15.py
def usingLoop(x):
y = []
for i in x:
if i not in y:
y.append(i)
return y
def usingSet(x):
return list(set(x))
OUTPUT:
150200107065 Page 30
Que.16) Create a class student with following member attributes: roll no, name, age
and total marks. Create suitable methods for reading and printing member variables.
Write a python program to overload ‘==’ operator to print the details of students
having same marks.
Program: Practical_16.py
class Student:
def __init__(self,rollNumber,name,age,totalMarks):
self.RollNumber = rollNumber
self.Name = name
self.Age = age
self.Marks = totalMarks
def __eq__(self,other):
def __str__(self):
.format(self.RollNumber,self.Name,self.Age,self.Marks)
return output
s1 = Student(1,'Hardik',22,700)
s2 = Student(2,'Nirav',20,680)
s3 = Student(3,'Dhruv',28,579)
s4 = Student(4,'Jay',40,690)
if(s1 == s2):
print(s1,s2)
150200107065 Page 31
OUTPUT:
150200107065 Page 32
Que.17) Create a class Employee with data members: name, department and salary.
Create suitable methods for reading and printing employee information.
Program: Practical_17.py
class Employee:
def __init__(self,name,department,salary):
self.Name = name
self.Department = department
self.Salary = salary
def __str__(self):
.format(self.Name,self.Department,self.Salary)
return output
e1 = Employee('Hardik','Computer',25000)
e2 = Employee('Dhruv','Civil',10000)
e3 = Employee('Sachin','Accounting',22000)
print(e1,e2,e3)
OUTPUT:
150200107065 Page 33
Que.18) Define a class Complex which represents the complex number. And overload
+ operator which add two complex objects.
Program : Practical_18.py
class Complex:
def __init__(self,real,imaginary):
self.Real = real
self.Imaginary = imaginary
def __str__(self):
.format(self.Real,self.Imaginary)
return output
def __add__(self,other):
temp = Complex(0,0)
return temp
c1 = Complex(4,5)
c2 = Complex(8,-2)
150200107065 Page 34
OUTPUT:
150200107065 Page 35
Que.19) Implement binary search algorithm to seach name for the given list of names.
Program: Practical_19.py
if arr[mid] == x:
return mid
else:
else:
return -1
list1.sort()
print('\nList : ',list1)
index = binary_search(list1,0,len(list1)-1,search)
if (index == -1):
else:
OUTPUT:
150200107065 Page 36
150200107065 Page 37
Que.20) Write a python program to arrange the characters of a given string 'welcome'
in an alphabetical order using insertion sort algorithm.
Program: Practical_20.py
def insertion_sort(arr):
val = arr[i]
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = val
return arr
print('\nInput : ',item)
print('\nOutput : ',insertion_sort(list(item)))
OUTPUT:
150200107065 Page 38
Que.21) Implement bubble sort algorithhm.
Program: Practical_21.py
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
bubbleSort(arr)
OUTPUT:
150200107065 Page 39
Que.22) Implement Quick sort algorithm.
Program: Practical_22.py
i = (low-1)
pivot = arr[high]
i = i+1
return (i+1)
if len(arr) == 1:
return arr
n = len(arr)
quickSort(arr, 0, n-1)
150200107065 Page 40
OUTPUT:
150200107065 Page 41
Que.23) Implement Hash table with its various functionality.
Program: Practical_23.py
def display_hash(hashTable):
for i in range(len(hashTable)):
for j in hashTable[i]:
print()
def Hashing(key):
hash_key = Hashing(key)
Hashtable[hash_key].append(value)
insert(HashTable,12,'Sachin')
insert(HashTable, 6, 'Vikky')
insert(HashTable,14,'Dipen')
150200107065 Page 42
insert(HashTable, 26, 'Urvesh')
display_hash (HashTable)
OUTPUT:
150200107065 Page 43
Que.24) Write a python program to know the current working directory and to print
all contents of the current directory. What changes we need to make in the program if
we wish to display the contents of only 'mysub' directory available in current
directory?
Program: Practical_24.py
import os
print(*(os.listdir()),sep='\n')
print(*(os.listdir('./'+directory)),sep='\n')
OUTPUT:
150200107065 Page 44
150200107065 Page 45
Que.25) Read a text file in Python and print no. of lines and no. of unique words
Program: Practical_25.py
numOfLines = 0
for line in f:
numOfLines += 1
text = open(fileName,'r').read()
text = text.lower()
words = text.split()
unique = []
unique.append(word)
OUTPUT:
150200107065 Page 46
Que.26) Write a python program to append data to an existing file 'python.py'. Read
data to be appended from the user. Then display the contents of entire file.
Program: Practical_26.py
list = []
while True:
line = input('')
if line == 'exit':
break
else:
line += '\n'
list.append(line)
fileName = 'python.py'
file = open(fileName,'a')
file.writelines(list)
file.close()
print(reader.read())
OUTPUT:
150200107065 Page 47
150200107065 Page 48
Que.27) Write a python program to retrieve string/s starting with m and having 5
characters from a) console and b) given file
def getResult(data):
return list(result)
# 1. From Console
list1 = []
while True:
line = input('')
if line == 'exit':
break
else:
list1.append(item)
print(getResult(list1))
150200107065 Page 49
# 2. From File
text = open(fileName,'r').read()
text = text.lower()
words = text.split()
print(getResult(words))
OUTPUT:
150200107065 Page 50
Que.28) Write a python program to retrieve name and date of birth (mm-ddyyyy) of
students from a given file student.txt.
Program: Practical_28.py
import re
import datetime
fileName = 'student.txt'
text = reader.read().splitlines()
finalSet = []
if(len(name) == 2):
try:
student = datetime.datetime.strptime(name[1],'%m-%d-%Y')
finalSet.append(line)
except ValueError:
pass
print(temp[0],' ',temp[1])
OUTPUT:
150200107065 Page 51
150200107065 Page 52
Que.29) Write a password generator in Python. Be creative with how you generate
passwords - strong passwords have a mix of lowercase letters, uppercase letters,
numbers, and symbols. The passwords should be random, generating a new password
every time the user asks for a new password. Include your code in a main method.
Program: Practical_29.py
import random
import array
import string
while True:
if MAX_LEN > 4:
break
else:
DIGITS = list(string.digits)
LOCASE_CHARACTERS = list(string.ascii_letters)[:26]
UPCASE_CHARACTERS = list(string.ascii_letters)[26:]
SYMBOLS = list(string.punctuation)
rand_digit = random.choice(DIGITS)
rand_upper = random.choice(UPCASE_CHARACTERS)
rand_lower = random.choice(LOCASE_CHARACTERS)
rand_symbol = random.choice(SYMBOLS)
150200107065 Page 53
temp_pass = rand_digit + rand_upper + rand_lower + rand_symbol
random.shuffle(temp_pass_list)
password = ""
for x in temp_pass_list:
password += x
print('\nAuto-Generated-Password is : ',password)
OUTPUT:
150200107065 Page 54
Que.30) Write a proper email matching regular expression and check the pattern of the
email.
Program: Practical_30.py
import re
regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
def check(email):
if(re.search(regex, email)):
print('\nValid Email')
else:
check(email)
OUTPUT:
150200107065 Page 55
Que.31) Write a python program to create a TCP/IP client-server chat application.
Make use of multithreading in your application.
Program: 31_Client.py
#Client
import socket
ClientSocket = socket.socket()
host = '127.0.0.1'
port = 5132
try:
ClientSocket.connect((host, port))
except socket.error as e:
print(str(e))
Response = ClientSocket.recv(1024)
while True:
if(Input == 'exit'):
break
ClientSocket.send(str.encode(Input))
Response = ClientSocket.recv(1024)
print(Response.decode('utf-8'))
ClientSocket.close()
150200107065 Page 56
#Server
import socket
import os
ServerSocket = socket.socket()
host = '127.0.0.1'
port = 5132
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
ServerSocket.listen(5)
def threaded_client(connection):
while True:
data = connection.recv(1024)
if not data:
break
connection.sendall(str.encode(reply))
connection.close()
150200107065 Page 57
while True:
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
ServerSocket.close()
OUTPUT:
150200107065 Page 58
Que.32) Write a program to plot different types of graphs using PyPlot.
Program: Practical_32.py
# py
import numpy as np
x = [1,2,3]
y = [2,4,1]
plt.plot(x, y)
plt.xlabel('Time')
plt.ylabel('Distance')
plt.title('Speed')
plt.show()
x1 = [1,2,3]
y1 = [2,4,1]
x2 = [1,2,3]
y2 = [4,1,3]
plt.xlabel('x - Axis')
plt.ylabel('y - Axis')
150200107065 Page 59
plt.title('Two Lines in One Plane.')
plt.legend()
plt.show()
# 3. Bar chart
left = [1, 2, 3, 4, 5]
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Bar Chart')
plt.show()
# 4. Histogram
ages = [2,5,70,40,30,45,50,45,43,40,44,
60,7,13,57,18,90,77,32,21,20,40]
bins = 10
plt.xlabel('Age')
plt.ylabel('No. of people')
plt.title('Histogram')
150200107065 Page 60
plt.show()
# 5. Scatter Plot
x = [1,2,3,4,5,6,7,8,9,10]
y = [2,4,5,7,6,8,9,11,12,12]
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Scatter Plot')
plt.legend()
plt.show()
# 6. Pie chart
slices = [4, 5, 9, 4]
plt.title('Pie Chart')
plt.show()
# 7. Curves
y = np.sin(x)
150200107065 Page 61
plt.plot(x, y)
plt.title('Curves')
plt.show()
OUTPUT:
150200107065 Page 62
150200107065 Page 63
Que.33) Implement classical ciphers using python.
Program: Practical_33.py
def encrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
else:
return result
OUTPUT:
150200107065 Page 64
Que.34) Create following regular polygons (regular means all sides the same lengths,
all angles the same) using for loop in turtle
• An equilateral triangle
• A square
• A hexagon
• An octagon.
Program: Practical_34.py
import turtle
wn = turtle.Screen()
# 1. An equilateral triangle
triangle = turtle.Turtle()
triangle.forward(50)
triangle.left(120)
# 2. A square
square =turtle.Turtle()
square.up()
square.forward(70)
square.down()
square.forward(50)
square.left(90)
# 3. Hexgon
150200107065 Page 65
hex =turtle.Turtle()
hex.up()
hex.forward(-70)
hex.down()
hex.forward(30)
hex.left(60)
# 4. An Octagon
oct =turtle.Turtle()
oct.up()
oct.forward(-170)
oct.down()
oct.forward(25)
oct.left(45)
turtle.exitonclick()
OUTPUT:
150200107065 Page 66
Que.35) Explain the major steps used to create widgets. Write a python program to
display a label upon clicking a push button.
Program: Practical_35.py
root = Tk(className="Pratical-35")
root.geometry("500x500")
def message():
w.pack()
button.place(x=25, y=80)
root.mainloop()
OUTPUT:
150200107065 Page 67
Que.36) Write a Python GUI program to create three push buttons using Tkinter. The
background color of frame should be different when different buttons are clicked.
Program: Practical_36.py
root = Tk()
root.geometry("500x500")
buttonRed.configure(width=10,activebackground="red",relief=FLAT)
buttonBlue.configure(width=10,activebackground="blue",relief=FLAT)
buttonGreen.configure(width=10,activebackground="green",relief=FLAT)
btn1 = canvas.create_window(100,10,anchor=NW,window=buttonRed)
btn2 = canvas.create_window(200,10,anchor=NW,window=buttonBlue)
btn3 = canvas.create_window(300,10,anchor=NW,window=buttonGreen)
150200107065 Page 68
canvas.pack()
root.mainloop()
OUTPUT:
150200107065 Page 69