You are on page 1of 23

ENROLLMENT NO.

:-160280107033
PYTHON PROGRAMMING(2180711)

Programming Assignment - 1

Q:-1 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?

Implementation:-

import os
print('---Contents of current working Directory---')
print(os.listdir(os.getcwd()))
print('---Contents of Scripts subdirectory---')
for subdir,dirs,files in os.walk('Scripts'):
for file in files:
print(file)

Output:-

BE|COMP.|SEM-8|LDCE PAGE| 1
Q:-2 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.

Implementation:-

print('---Apeend the data to Exiting File---')


data=input('Enter text to append the content in file:')
with open('Python.py','a') as f:
f.write(data)
print('Content of File:')
with open('Python.py','r') as fin:
print(fin.read())

Output:-
Q:-3 Write a python program to retrieve strings starting with m and having 5 characters.

Implementation:-

import re
print('---String starting with m and having 5 characters---')
with open('Text.txt','r') as cf:
text=cf.read()
print('List of String::-')
text1=re.findall(r'\bm\w{4,10}',text)
print(text1)

Output:-
Q:-4 Write a python program to retrieve name and date of birth (mm-ddyyyy) of
students from a given file student.txt.

Implementation:-

import datetime,re
print('---Retrive Date of Birth from file---')
with open('Text.txt','r') as cf:
datestring=cf.read()
print('Date of Birth::-')
text1=re.findall('(\d{2})[-](\d{2})[-](\d{4})$',datestring)
if(text1!=[]):
print(text1)

Output:-
Q:-5 Write a python program to create a TCP/IP client-server chat application.

Implementation:-

SERVER PROGRAM:-

import socket as s
import time as t
def Main():
host='127.0.0.1'
port=1234
mySocket=s.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr=mySocket.accept()
print('Connection from:-',str(addr))
while True:
data=conn.recv(1024).decode()
if not data:
break
print('Client Says:',str(data))
data=input('Enter Message:')
conn.send(data.encode())
conn.close()

if name ==' main ':


print('---Chat Application---')
Main()

CLIENT PROGRAM:-

import socket as s
def Main():
host='127.0.0.1'
port=1234
mySocket = s.socket()
mySocket.connect((host, port))
msg = input('Enter Message:')
while msg!='q':
mySocket.send(msg.encode())
data=mySocket.recv(1024).decode()
print('Server Says:', str(data))
msg = input('Enter Message:')
mySocket.close()

if name == ' main ': print('---


Chat Application---') Main()
Output:-
Q:-6 Write a Python program that counts the number of occurrences of the character in the
given string. Provide two implementations: recursive and iterative.

Implementation:-

def char_frequency(str1):
dict={}
for n in str1:
keys=dict.keys()
if n in keys:
dict[n]+=1
else:
dict[n]=1
return dict

print('---Count the No. of Occurence of Character In String---')


string=input('Enter String::-')
print('Occurence of Character::-')
print(char_frequency(string))

Output:-
Q:-7 Write a python program to search a specific value from a given list of values using binary
search method.

Implementation:-

def Binary1(L,x,low,high):
mid=(int) ((low+high)/2)
if L[mid]==x:
return mid+1;
elif (L[mid] <= x):
return Binary1(L,x,mid+1,high)
elif (L[mid >= x]):
return Binary1(L,x,low,mid-1)
else:
return -1
L=[]
print('---Binary Search in List---')
n=int(input('Enter the No. of Element::-'))
L=list(map(int,input('Enter the Element::-\n').split()))[:n]
print('List::-',L)
x=int(input('Enter the no. which is find into list::-'))
print('No. is present at Position',Binary1(L,x,0,n-1))

Output:-
Q:-8 Write a python program to arrange the characters of a given string 'welcome' in an
alphabetical order using insertion sort algorithm.

Implementation:-

def Insertion(S):
for j in range(len(S)):
x=S[j]
i=j-1
while i>=0 and S[i]>x:
S[i+1]=S[i]
i=i-1
S[i+1]=x
print('Sorted String is::-')
for k in range(len(S)):
print(L[k],end='')
print('---Insertion Sort---')
S=input('Enter String::-')
L=[]
for i in range(len(S)):
L.append(S[i])
Insertion(L)

Output:-
Q:-9 Write a python program in which Maruti and Santro sub classes implement the abstract
methods of the super class Car.

Implementation:-

from abc import ABC, abstractmethod


class Car(ABC):
def set_color(self,color): pass
def set_price(self,price): pass

class Maruti(Car):
def set_color(self,color):
self.color=color
print('Color=',self.color)
def set_price(self,price):
self.price=price
print('Price=',self.price,'Lakh')

class Santro(Car):
def set_color(self,color):
self.color=color
print('Color=',self.color)
def set_price(self,price):
self.price=price
print('Price=',self.price,'Lakh')

print('---Abstract Method---')
C=Maruti()
print('Description of Maruti Car::-')
C.set_color('Blue')
C.set_price(12.4)
S=Santro()
print('Description of Santro Car::-')
C.set_color('Red')
C.set_price(15.6)

Output:-
Q:-10 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

Implementation:-

class Student:
def read_data(self):
self.rollno=int(input('Enter Roll No.:-'))
self.name = (input('Enter Name:-'))
self.age = int(input('Enter Age:-'))
self.mark = int(input('Enter Toatal Marks:-'))
def print_data(self):
print('Roll no. ==',self.rollno)
print('Name ==',self.name)
print('Age ==',self.age)
print('Total
Mark==',self.mark)
def eq (self, other):
if self.mark==other.mark:
self.p=1
else:
self.p=0
return self.p

s=[]
print('---Operator (==) overloading ---')
n=int(input('Enter the No. of Student:-'))
for i in range(n):
s.append(Student())
for i in range(len(s)):
s[i].read_data()
for i in range(len(s)):
for j in range(i+1,len(s)):
t=(s[i]==s[j])
if t==1:
print('\n Student detail having same marks:\n')
s[i].print_data()
s[j].print_data()
Output:-
Q:-11 Create following regular polygons (regular means all sides the same lengths, all angles
the same) using for loop in turtle
a. An equilateral triangle
b. A square
c. A hexagon
d. An octagon

Implementation:-

import turtle as tl
side=int(input('Enter No. of Sides:-'))
myPen=tl.Turtle()
myPen.shape('turtle')
myPen.color('red')

def Draw_Polygon(side):
Angle=360/side
length=600/side
myPen.penup()
myPen.goto(-length/2,-length/2)
myPen.pendown()
for i in range(0,side):
myPen.forward(length)
myPen.left(Angle)

Draw_Polygon(side)
tl.done()

Output:-
Q:-12 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.

Implementation:-

from tkinter import *


root=Tk()

def grey(*args,**kwargs):
root.configure(background='grey')
def bthing():
root.configure(background='red')
def bthing1():
root.configure(background='green')
def bthing2():
root.configure(background='blue')
root.after(1000,grey)
Button(text='RED Button',command=bthing).pack()
Button(text='GREEN Button',command=bthing1).pack()
Button(text='BLUE Button',command=bthing2).pack()
root.configure(background='grey')
root.geometry('200x200')

root.mainloop()

Output:-
Q:-13 Write a Python program to print Fibonacci series upto n terms.

Implementation:-

Implementation:-

print('---Fibonacci Series---')
n=int(input('Enter Series Range(n>2):-'))
arr=[0,1]
a=0
b=1
print('Fibonacci Series is:-')
while n!=2:
c=a+b
a=b
b=c
n-=1
arr.append(c)
print(arr)

Output:-
Q:-14 Write a Python program to check whether the given no is Armstrong or not using user
defined function.

Implementation:-

def Armstrong(n):
order=len(str(n))
sum=0
t=n
while t>0:
y=t%10
sum=sum+y**order
t=t//10
if n==sum:
print('No. is Armstrong')
else:
print('No is not Armstrong')
print('---Armstrong Number---')
N=int(input('Enter the No.::-'))
Armstrong(N)

Output:-
Q:-15 Write a Python program to implement the concept of inheritance.

Implementation:-

class student:
def init (self,name=None,Enr=0):
self.name=name
self.Enroll=Enr

def display(self):
return self.name+ '\t\t' + str(self.Enroll)

class result(student):
def init (self,name=None,Enr=0,marks=[]):
student. init (self,name,Enr)
self.marks=marks

def getResult(self):
total=0
len2=len(self.marks)
c=0
for i in self.marks:
if i>8:
c=c+1
if c==2:
self.result='PASS'
else:
self.result='FAIL'
return self.result

def displayResult(self):
return self.display() + '\t\t' + self.getResult()

print('---Concept of Inheritance---')
mark=[]
n=int(input('Enter the No. of Student:-'))
while n>0:
name=input('Enter Name:')
enr=int(input('Enter Roll No.:-'))
mark.append(int(input('Enter mark of Sub1 out of 20:-')))
mark.append(int(input('Enter mark of Sub2 out of 20:-')))
s2=result(name,enr,mark)
print('Name\tRoll No.\tResult')
print(s2.displayResult())
n=n-1
Output:-
Q:-16 Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.

Implementation:-

class Employee:
empCount=0
def init (self,name,salary):
self.name=name
self.salary=salary
Employee.empCount+=1

def displayCount(self):
print('Total Employee is:-',Employee.empCount)

def display(self):
print('Name: ',self.name,' Salary: ',self.salary)

print('---Retrive the Information of Employee---')


emp1=Employee('SURESH',16000)
emp2=Employee('KRUNAL',15000)
emp1.display()
emp2.display()

Output:-
Q:-17 Write a Python program to overload + operator.

Implementation:-

class Complex:
def init (self,a,b):
self.a=a
self.b=b

def add (self, other):


self.a=self.a + other.a
self.b=self.b + other.b
return self

def display(self): print(self.a,'+


(',self.b,')i',sep='')

print('---Addition(+) Opearator Overloading---')


print('Enter the real and Virtual Element of Complex A:-')
a,b=map(int,input().split())
A=Complex(a,b)
print('Enter the real and Virtual Element of Complex B:-')
c,d=map(int,input().split())
B=Complex(c,d)
print('Complex No. A
is:-') A.display()
print('Complex No. B is:-')
B.display()
print('A + B is:-')
C=A+B
C.display()

Output:-
Q:-18 Create a text file in Python and print no. of lines and no. of unique words.

Implementation:-

from collections import Counter as cnt


print('---Count The Unique Words---')
file_name=input('Enter File Name with extension:')
try:
def read_w(file_name):
with open(file_name,'r') as file_object:
word=[]
for line in file_object:
word+=line.split()
return word

words_list=read_w(file_name)
count_word=cnt(words_list)
print(count_word)
except OSError:
print('Filename doesn\'t Exit!!')

Output:-
Q:-19 Write Python program to display a label on clicking a push button.

Implementation:-

from tkinter import *


tk=Tk()
entry=Entry(tk)
entry.pack()
print('---Print Label using Push Button---')
str=input('Enter the Label:-')
entry.insert(INSERT,str)
def push():
print('Push by tkinter:=-',end='')
print(entry.get())
btn=Button(tk,text='PUSH',command=push)
btn.pack()
tk.mainloop()

Output:-

You might also like