You are on page 1of 54

SR DATE PRACTICAL PG No.

SIGNATURE
.
NO
.
1. Develop programs to understand the control
structures of python
2. Develop programs to learn different types of
structures (list, dictionary, tuples) in python
3. Develop programs to learn concept of
functions scoping, recursion and list
mutability.
4. Develop programs to understand working of
exception handling and assertions.
5. Develop programs for data structure
algorithms using python – searching, sorting
and hash tables.
6. Develop programs to learn regular
expressions using python.
7. Develop chat room application using
multithreading.
8. Learn to plot different types of graphs using
PyPlot.
9. Learn to use different types of Mathematical
function using NumPy.
10. Draw different types of graphics using
MatplotLib.
11. Learn to plot different types of graphs using
NetworkX.
PRACTICAL NO: - 01
AIM: Develop programs to understand the control structures of python.

01 (1). Write a python program that finds the factorial of a natural number n.

PROGRAM:

num = int(input("Enter a number: "))


factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

OUTPUT:
01 (2). Write a Python Program to find those numbers which are divisible by 7
and multiple of 5, between 1500 and 2700.
PROGRAM:

nl=[]
for x in range(1500, 2701):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print (','.join(nl))

OUTPUT:
01 (3). Write a Python program to construct the following pattern, using a nested
for loop.
*
**
***
****
*****
****
***
**
*

PROGRAM:

n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')

for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
OUTPUT:
01 (4). Write a Python program that accepts a word from user and reverse it
(without using the reverse function)
PROGRAM:

word = input("Input a word to reverse: ")


for char in range(len(word) - 1, -1, -1):
print(word[char], end="")
print("\n")

OUTPUT:
01 (5). Write a Python program to check whether an alphabet is a vowel or
consonant.
PROGRAM:

ch = input("Enter a alphabet: ")


if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
OUTPUT:
01 (6). Write a Python program to find reverse of given number using user
defined function.

PROGRAM:

def reverseNum(num) :
rev_num = 0
while(num) :
rem = num % 10
rev_num = rev_num* 10 + rem
num //= 10
return rev_num
if name == " main " :
num = int(input('Enter a number: '))
print('Reverse number is: ', reverseNum(num))

OUTPUT:
01 (7). Write a Python program to check whether the given no is Armstrong or
not using user defined function.
PROGRAM:

def power(x, y):


if y == 0:
return 1
if y % 2 == 0:
return power(x, y // 2) * power(x, y // 2)
return x * power(x, y // 2) * power(x, y // 2)
def order(x):
n=0
while (x != 0):
n=n+1
x = x // 10
return n
def isArmstrong(x):
n = order(x)
temp = x
sum1 = 0
while (temp != 0):
r = temp % 10
sum1 = sum1 + power(r, n)
temp = temp // 10
return (sum1 == x)
x = 153
print(isArmstrong(x))
x = 1253
print(isArmstrong(x))
OUTPUT:
01 (8). To write a Python program to find first n prime numbers.
PROGRAM:

numr=int(input("Enter range:"))
print("Prime numbers:",end=' ')
for n in range(1,numr):
for i in range(2,n):
if(n%i==0):
break
else:
print(n,end=' ')

OUTPUT:
01 (9). Write a Python program to print Fibonacci series upto n terms.
PROGRAM:

nterms = int(input("How many terms? "))


n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

OUTPUT:

01 (10). Give the output of following Python code:


I. myStr = "GTU is the best University"
print (myStr [15 : : 1] )
print (myStr [-10 : -1 : 2])

OUTPUT:

II. t = (1, 2, 3, (4, ), [ 5, 6] )


print (t[ 3 ])
t[4][0] = 7
print (t)

OUTPUT:
III. I=[(x, y)for x in [1,2,3] for y in [3,1,4]if x != y]
print (I)

OUTPUT:

IV. str1 = "This is Pyhton"


print ("Slice of String : ", str1[1 : 4 : 1])
print ("Slice of String : ", str1[0 : -1 : 2])

OUTPUT:
PRACTICAL NO: - 02
AIM: Develop programs to learn different types of structures (list,
dictionary, tuples) in python.

02 (1). Write a python program that finds the largest element form given number.

PROGRAM:

list1 = [10, 20, 4, 45, 99]


list1.sort()
print("Largest element is:", list1[-1])

OUTPUT:
02 (2). Write a Python program which will return the sum of the numbers in the
array, returning 0 for an empty array. Except the number 13 is very unlucky, so
it does not count and number that come immediately after 13 also do not count.
Example: [1, 2, 3, 4] = 10 [1, 2, 3, 4, 13] = 10 [13, 1, 2, 3, 13] = 5
PROGRAM:

def sum13(nums):
i=0
while i < len(nums):
if nums[i] == 13:
del nums[i:i+2]
continue
i += 1
return sum(nums)
print(sum13([1,2,2,1,13]))
print(sum13([13,2,2,1,13]))

OUTPUT:
02 (3). Write a Python program which takes a list and returns a list with the
elements "shifted left by one position" so [1, 2, 3] yields [2, 3, 1]. Example: [1, 2,
3] → [2, 3, 1] [11, 12, 13] → [12, 13, 11]
PROGRAM:

def leftrotate(lis,n):
output_list=[]
for i in range(1,len(lis)):
output_list.append(lis[i])
for i in range(0,1):
output_list.append(lis[i])
return output_list
rotate_num=1
l=[1,2,3,4]
print(leftrotate(l,rotate_num))

OUTPUT:
02 (4). 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:
import os
print(os.getcwd())
print("*****Content of Current Directory*****")
print(os.listdir(os.getcwd()))
print("*****Content of Sub Directory in Current Directory*****")
print(os.listdir('8th sem'))

OUTPUT:
02 (5). Write a program to count the numbers of characters in the string and
store them in a dictionary data structure
PROGRAM:

str=input("enter string : ")


f = {}
for i in str:
if i in f:
f[i] += 1
else:
f[i] = 1
print(f)

OUTPUT:
02 (6). Write a program to use split and join methods in the string and trace a
birthday with a dictionary data structure.
PROGRAM:

pen='+'
pin=['H','E','L','L','O']
print("Joining")
print(pen.join(pin))
c=pen.join(pin)
print("Splitting")
print(c.split('+'))
people={
'Netaji':{
'birthday':'Aug 15'
},
'Manaswi':{
'birthday':'Mar 21'
},
'Chandrika':{
'birthday':'July 7'
}
}
labels={
'birthday':'birth date'
}
name=input("Name:")
request=input('birthday(b)?')
if request=='b':
key='birthday'
if name in people:
print("%s's %s is %s." % (name, labels[key], people[name][key]))
OUTPUT:
PRACTICAL NO: - 03
AIM: Develop programs to learn concept of functions scoping, recursion and
list mutability.

03 (1). Write a Python program to create class GTU with attributes like class
variable cnt, instance variables x and y, instance methods get_value and
print_value.

PROGRAM:

class GTU():
def init (self):
self.cnt = ""

def get_value(self,x,y):
self.x= input("enter x: ")
self.y=input("enter y:")

def print_value(self):
print("value of x is :"+self.x)
print("value of y is :"+self.y)
cnt = GTU()
cnt.get_value(int,int)
cnt.print_value()

‘OUTPUT:
03(2). Create a Python program to read a text file and do following: I. Print no. of
lines II. Print no. of unique words III. Store each word with its occurrence in
dictionary.

1. Print no. of lines


PROGRAM:

f1=input("Enter file name: ")


num_lines=0
with open(f1, 'r') as f:
for line in f:
num_lines+=1
print("Number of lines:")
print(num_lines)

OUTPUT:
2. Print no. of unique words
PROGRAM:

count={}
f1 =input("Enter file name :")
for w in open(f1).read().split():
if w in count:
count[w]+=1
else:
count[w]=1
for words,times in count.items():
print(words,"isfind",times,"times")

OUTPUT:
3. Store each word with its occurrence in dictionary

PROGRAM:

f1 = input("Enter file name: ")


word=input("Write Word To Search:")
k=0
with open(f1,'r') as f:
for line in f:
words=line.split()
for i in words:
if(i==word):
k=k+1
print("No. Of Occurrences word:")
print(k)

OUTPUT:
03 (3). Write a Python program to read a text file and do following:
1. Print no. of words 2. Print no. statements

1. Print no. of words

PROGRAM:

word=0
with open("h1.txt","r") as f:
for line in f:
words=line.split()
word+=len(words)
print("number of words:")
print(word)

OUTPUT:
2. Print no. statements.

PROGRAM:

f1=input("Enter file name: ")


num_statements=0
with open(f1, 'r') as f:
for line in f:
num_statements += 1
print("Number of statements:")
print(num_statements)

OUTPUT:
03 (4). Read a text file in Python and print no. of lines and no. of unique
words.

1 print no. of lines

PROGRAM:
file = open("sample.txt","r")
Counter = 0
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
print("This is the number of lines in the file")
print(Counter)

OUTPUT:
2. print no. of unique words

PROGRAM:
text_file = open('sample.txt', 'r')
text = text_file.read()
text = text.lower()
words = text.split()
words = [word.strip('.,!;()[]') for word in words]
words = [word.replace("'s", '') for word in words]
unique = []
for word in words:
if word not in unique:
unique.append(word)
unique.sort()
print(unique)

OUTPUT:
03 (5). 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:

f1=open("emp.txt","r")
data2=f1.read()
f1.close()
f2=open("python.py","a")
f2.write(data2)
print("Append data successfully")
f2.close()

OUTPUT:
03 (6). Write a python program to retrieve name and date of birth (mm-dd-
yyyy) of students from a given file student.txt.

PROGRAM:

import re
import datetime
filepath = 'student.txt'
with open(filepath, 'r') as f:
file = f.read()
a = file.split('\n')
print(a)
res = []
for item in a:
b = str(item).split(' ')
res.append(b)
for item in res: print(item)
OUTPUT:
03 (7). Write a python program that reads a text file and changes the file by
capitalizing each character of file.

PROGRAM:
for line in open('sample.txt'):
print(line.upper(), end='')

OUTPUT:
PRACTICAL NO: - 04
AIM: Develop programs to understand working of exception handling and
assertions Classes and Object-Oriented Programming

04 (1). Write a Python program to implement the concept of inheritance.


PROGRAM:
class Person(object):
def init (self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
emp = Person("Geek1")
print(emp.getName(), emp.isEmployee())
emp = Employee("Geek2")
print(emp.getName(), emp.isEmployee())

OUTPUT:
04 (2). Create a class Employee with data members: name, department and
salary. Create suitable methods for reading and printing employee information.
PROGRAM:
class Empoloyee():
empCount = 0
def init (self, name, department, salary):
self.name= name
self.department= department
self.salary= salary
Empoloyee.empCount += 1
def show_info(self):
print("\n\n\t-> Employee Detail <-")
print("Name:-->",
self.name,"\nsalary:-->", self.department,"\nSalary:-->", self.salary)
employee= []
for i in range(1,3):
print("\t-> Enter Employee Detail <-")
name=input('Enter Name:-->')
department=input('Enter Deparment:-->')
salary=float(input('Enter Salary:-->'))
employee.append(Empoloyee(name,department,salary))
for employees in employee:
employees.show_info()
OUTPUT:
04 (3). Write a Python program to overload + operator.

PROGRAM:

class Point:
def init (self, x = 0, y = 0):
self.x = x
self.y = y
def str (self):
return "({0},{1})".format(self.x,self.y)
def add (self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
p1 =Point(6,3)
p2 =Point(-4,4)
print("OPERATOR (+) OVERLOADING ")
print(p1 + p2)

OUTPUT:
04 (4) Write a Python program that counts the number of occurrences of the
character in the given string. Provide two implementations: recursive and
iterative.

PROGRAM:

string = input("Enter String: ")


char = input("Enter Character to check: ")
i=0
count = 0
while(i < len(string)):
if(string[i] == char):
count = count + 1
i=i+1
print("The total no. of times the character ->", char, " has Counted = " , count)

OUTPUT:
04 (5). Write a python program in which Maruti and Santro sub classes
implement the abstract methods of the super class Car.
PROGRAM:
from abc import ABC,abstractmethod
class car(ABC):
@abstractmethod
def color(self):
pass
class maruti(car):
def init (self):
print("child class maruti\n")
def color(self,cname):
self.cname=cname
print("color is :",cname)
class santro(car):
def init (self):
print("child class santro")
def color(self,cname):
self.cname=cname
print("color is:",cname)
s=santro()
m=maruti()
s.color("black")
m.color("white")

OUTPUT:
04 (6). 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:
class Student():
def init (self, r_no, name, age, marks):
self.r_no = r_no
self.name = name
self.age = age
self.marks = marks
def displayStudent(self):
print("Roll no : ", self.r_no, "Name : ", self.name, "Age: ", self.age, "Marks: ",
self.marks)
def str (self):
return "({0},{1})".format(self.r_no, self.name, self.age, self.marks)
def eq (self, other):
if (self.marks == other.marks):
return self.marks == other.marks
stu = {}
for i in range(1, 3):
print("\n\tEnter Details for Students %d" % (i))
r_no = int(input("Enter Roll no:"))
name = input("Enter Name:")
age = int(input("Enter Age:"))
marks = input("Enter Marks:")
stu[i] = (Student(r_no, name, age, marks))
for j in range(1, 3):
if stu[j] == stu[j + 1]:
stu[j].displayStudent()
else:
print("\nMarks of the students are not equal")

OUTPUT:
PRACTICAL NO: - 05
AIM: Develop programs for data structure algorithms using python –
searching, sorting and hash tables.

05 (1). Write a Python program to search a specific value from a given list of
values using binary search method.

PROGRAM:
def binary_sort(sorted_list, length, key):
start = 0
end = length-1
while start <= end:
mid = int((start + end)/2)
if key == sorted_list[mid]:
print("\nEntered number %d is present at position: %d" % (key, mid))
return -1
elif key <sorted_list[mid]:
end = mid - 1
elif key >sorted_list[mid]:
start = mid + 1
print("\nElement not found!")
return -1
lst = []
size = int(input("Enter size of list:"))
for n in range(size):
numbers = int(input("Enter number:"))
lst.append(numbers)
lst.sort()
print('\n\nThe sorted list is:', lst)
x = int(input("\nEnter the number to search: "))
binary_sort(lst, size, x)
OUTPUT:
05 (2). Write a python program to arrange the characters of a given string
'welcome' in an alphabetical order using insertion sort algorithm.

PROGRAM:

def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = ["W", "E", "L", "C", "O", "M", "E"]
print("Original Character:",nlist)
insertionSort(nlist)
print("Sorted Character:",nlist)

OUTPUT:
05 (3). To write a Python Program to perform Selection sort.

PROGRAM:

def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)

OUTPUT:
05 (4). Write a python program that sorts the list [34, 25, 81, 12, 5] using merge
sort.

PROGRAM:

def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print("\nMerging list ",nlist)
nlist = [5,3,2,4,1,0]
mergeSort(nlist)
print(nlist)
OUTPUT:
PRACTICAL NO: - 06
AIM: Develop programs to learn regular expressions using python.

6(1).Write a python program to retrieve strings starting with m and having 5


characters.

PROGRAM:

import re
word=input('Enter The Character: ')
l=len(word)
if(re.match('m',word) and l==5):
print('valid String :-',word)
else:
print('The string is not started with "M":-',word)

OUTPUT:
PRACTICAL NO: - 07
AIM: Develop chat room application using multithreading.

7(1).Write a python program to create a TCP/IP client-server chat application.

Chat_server.py:-

import socket
import os
from _thread import *
ServerSocket = socket.socket()
host = '127.0.0.1'
port = 1233
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Waitiing for a Connection..')
ServerSocket.listen(5)
def threaded_client(connection):
connection.send(str.encode('Welcome to the Servern'))
while True:
data = connection.recv(2048)
reply = 'Server Says: ' + data.decode('utf-8')
if not data:
break
connection.sendall(str.encode(reply))
connection.close()
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()

client.py:-

import socket
ClientSocket = socket.socket()
host = '127.0.0.1'
port = 1233
print('Waiting for connection')
try:
ClientSocket.connect((host, port))
except socket.error as e:
print(str(e))
Response = ClientSocket.recv(1024)
while True:
Input = input('Say Something: ')
ClientSocket.send(str.encode(Input))
Response = ClientSocket.recv(1024)
print(Response.decode('utf-8'))
ClientSocket.close()
OUTPUT:
PRACTICAL NO: - 08
AIM: Learn to plot different types of graphs using PyPlot.
08 (1). Write a simple python program that draws a line graph where x = [1,2,3,4]
and y = [1,4,9,16] and gives both axis label as “X-axis”and “Y-axis” using pylab.

PROGRAM:
from matplotlib import pyplot as plt
x = [1,2,3,4]
y = [1,4,9,16]
plt.plot(x,y)
plt.title('Line Graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

OUTPUT:
PRACTICAL NO: - 09
AIM: Learn to use different types of Mathematical function using NumPy.
PRACTICAL NO: - 10
AIM: Draw different types of graphics using MatplotLib.
PRACTICAL NO: - 11
AIM: Learn to plot different types of graphs using NetworkX.

You might also like