0% found this document useful (0 votes)
4 views69 pages

Python Practical

Uploaded by

Hari Maheta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views69 pages

Python Practical

Uploaded by

Hari Maheta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Python ( 2180711 )

Name :- Maheta Harilal

Enrollment No. :- 150200107065

Division/Batch :- E/E1

Sr Title Page Date Sign


no. No.

1. Create a program that asks the user to enter their 6 15/12/2020


name and their age. Print out a message addressed
to them that tells them the year that they will turn
100 years old. [CO-1]
2. Ask the user for a number. Depending on whether 7 to 8 15/12/2020
the number is even or odd, print out an appropriate
message to the user [CO-1]

1. If the number is a multiple of 4, print out a


different message.

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 user. If not, print a different appropriate
message.
3. Take a list, say for example this one: a = [1, 1, 2, 3, 9 to 15/12/2020
5, 8, 13, 21, 34, 55, 89] and write a program that 11
prints out all the elements of the list that are less
than 5 also perform following task: [CO-1]

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.

2. Write this in one line of Python.

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.

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]

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. [CO-1]

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]

• Keep the game going until the user types “exit”


• Keep track of how many guesses the user has
taken, and when the game ends, print this out.

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

20. . Write a python program to arrange the characters 37 2/2/2021


of a given string 'welcome' in an alphabetical order
using insertion sort algorithm. [CO-1][CO-4]
21. Implement bubble sort algorithhm. [CO-1][CO-4] 38 2/2/2021
22. Implement Quick sort algorithm. [CO-1][CO-4] 39 to 9/2/2021
40

150200107065 Page 3
23. Implement Hashtable with its various functionality. 41 to 9/2/2021
[CO-1][CO-4] 42

24. Write a python program to know the current 43 to 16/2/2021


working directory and to print all contents of the 44
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? [CO-4]
25. Read a text file in Python and print no. of lines and 45 23/2/2021
no. of unique words [CO1][CO-4]
26. Write a python program to append data to an 46 to 2/3/2021
existing file 'python.py'. Read data to be appended 47
from the user. Then display the contents of entire
file. [CO-1][CO-3]
27. Write a python program to retrieve string/s starting 48 to 9/3/2021
with m and having 5 characters from a) console 49
and b) given file [CO-4]
28. Write a python program to retrieve name and date 50 to 16/3/2021
of birth (mm-ddyyyy) of students from a given file 51
student.txt. [CO-4]
29. Write a password generator in Python. Be creative 52 to 23/3/2021
with how you generate passwords - strong 53
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.
[CO-4]
30. Write a proper email matching regular expression 54 30/3/2021
and check the pattern of the email. [CO-4]
31. Write a python program to create a TCP/IP client- 55 to 6/4/2021
server chat application. Make use of multithreading 57
in your application. [CO-4]
32. Write a program to plot different types of graphs 58 to 13/4/2021
using PyPlot. [CO-4] 62

33. Implement classical ciphers using python. [CO-4] 63 20/4/2021

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.

35. Explain the major steps used to create widgets. 66 27/4/2021


Write a python program to display a label upon
clicking a push button. [CO-4]
36. Write a Python GUI program to create three push 67 to 27/4/2021
buttons using Tkinter. The background color of 68
frame should be different when different buttons
are clicked. [CO-4]

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();

name = input('\nWhat is your name: ')

age = int(input('\nHow old are you: '))

answerYear = str((currentYear.year - age)+100)

print('\n{} will be 100 years old in the year {}.'.format(name,answerYear));

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

1. If the number is a multiple of 4, print out a different message.

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

user. If not, print a different appropriate message.

Program : Practical_2.py

1.

number = int(input('\nEnter a number :'))

if number % 4 == 0:

print('\nThe number {} is multiple of 4.'.format(number))

elif number % 2 == 0:

print('\nThe number {} is even.'.format(number))

else:

print('\nThe number {} is odd.'.format(number))

2.

num = int(input('\nEnter a number to check :'))

check = int(input('\nEnter a number to divide by :'))

150200107065 Page 7
if num % check == 0:

print('\n{} divide evenly by {}.'.format(num,check))

else:

print('\n{} does not divide evenly by {}.'.format(num,check))

OUTPUT :

150200107065 Page 8
Que.3) Take a list, say for example this one:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

and write a program that prints out all the elements of the list that are less than 5

also perform following task:

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.

2. Write this in one line of Python.

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 = []

print('\nEnter number to add in the list.(Press Q to Quit)\n')

while True:

data = input('Enter Number :')

if(str(data).upper() == "Q"):

break

else:

userData.append(int(data))

output = ""

150200107065 Page 9
for data in userData:

if data < 5:

output += str(data)+" "

newList = []

for data in userData:

if data < 5:

newList.append(data)

print('\nOutput Without Creating New List : {}'.format(output)) # Without creating


new list

print('\nOutput With Creating New List : {}'.format(newList)) # Without creating new


list

2.

answer = [data for data in userData if data < 5]

print('\nOne Line Answer : {}'.format(answer)) # One Line Answer

3.

userInput = int(input('\nEnter Number :'))

newOutput = ""

for data in userData:

if data < userInput:

newOutput += str(data)+" "

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

number = int(input('\nEnter Number : '))

listRange = list(range(1,number+1))

divisorList = []

for value in listRange:

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):

return [x for x in range(1,number+1) if number%x == 0]

number = int(input('\nEnter Number : '))

print('\nAnswer : {}'.format(getfactors(number)))

OUTPUT :

150200107065 Page 13
Que.6) Take two lists, say for example these two:

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]

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 = []

print('\nEnter List-A value.(Press Q to Quit)\n')

while True:

data = input('Enter Number :')

if(data.upper() == 'Q'):

break

else:

inputA.append(int(data))

print('\nEnter List-B value.(Press Q to Quit)\n')

while True:

data = input('Enter Number :')

150200107065 Page 14
if(data.upper() == 'Q'):

break

else:

inputB.append(int(data))

result = [items for items in inputA if items in inputB]

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

word=input('\nEnter Word : ')

reverseWord=word[::-1]

if word == reverseWord:

print('\nWithout Loop Output : This String is palindrome')

else:

print('\nWithout Loop Output : This String is not palindrome')

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:

print('\nWith Loop Output : This String is palindrome')

else:

print('\nWith Loop Output : This String is not palindrome')

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)):

for character in str1:

if ord(character) - ord(str2[counter]) == 0:

counter += 1

else:

return False

else:

return False

if counter == len(str1):

return True

string1 = input('\nEnter String-1 : ').lower()

string2 = input('\nEnter String-2 : ').lower()

if(checkString(string1,string2)):

print('\nBoth the Strings are equal')

else:

print('\nBoth the Strings are not equal')

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

inp_str = input('\nEnter String : ')

out = {x : inp_str.count(x) for x in set(inp_str )}

print('Occurrence of all characters in {} is : '.format(inp_str))

print(json.dumps(out, indent=4, sort_keys=True))

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

sizeOfList = int(input('\nEnter List Length : '))

oldList = []

for item in range(0,sizeOfList):

oldList.append(random.randint(0,MAX_VALUE))

newList = [item for item in oldList if item % 2 == 0]

oldList.sort()

newList.sort()

print('\nOriginal List(Sorted Order) : ',*oldList)

print('\nNew List(Sorted Order)',*newList)

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 the game going until the user types “exit”

• 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):

if(number > correctNumber):

print('\nYour number is Big..!!')

return False

elif(number < correctNumber):

print('\nYour number is Small..!!')

return False

else:

print('\nYou won the Game in {} try..!!'.format(numberOfTry))

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:

number = input('\nEnter the number : ')

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:

for i in range(2, num):

if (num % i) == 0:

flag = True

break

return flag

def printMessage(number,result):

if result:

print(number, "is not a Prime Number.")

else:

print(number, "is a Prime Number.")

number = int(input('Enter Number : '))

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:

for index in range(2,modNumber):

if modNumber % index == 0:

flag = True

break

printMessage(number,flag)

else:

print('\nList Comprehensions')

primes = [index for index in range(2,modNumber) if modNumber % index == 0]

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):

return [a_list[0], a_list[len(a_list)-1]]

lst1 = []

lst1 = [int(item) for item in input("\nEnter the list items : ").split()]

print('\nGiven List : ',lst1)

print('\nNew List : ',list_ends(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]

elif count > 2:

fib = [1,1]

while i < (count - 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))

list1 = [int(item) for item in input("\nEnter the list items : ").split()]

print('\nYour List :',list1)

print('\nUsing Loop : ',usingLoop(list1))

print('\nUsing Set : ',usingSet(list1))

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):

return self.Marks == other.Marks

def __str__(self):

output = '\nRollNumber : {}\nName : {}\nAge : {}\nMarks : {}\n'\

.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):

output = '\nName : {}\nDepartment : {}\nSalary : {}\n'\

.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):

output = '{} + {}i'\

.format(self.Real,self.Imaginary)

return output

def __add__(self,other):

temp = Complex(0,0)

temp.Real = self.Real + other.Real

temp.Imaginary = self.Imaginary + other.Imaginary

return temp

c1 = Complex(4,5)

c2 = Complex(8,-2)

print('\nFirst Number : ',c1)

print('Second Number : ',c2)

print('After Adding : ',c1+c2)

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

def binary_search(arr, low, high, x):

if high >= low:

mid = (high + low) // 2

if arr[mid] == x:

return mid

elif arr[mid] > x:

return binary_search(arr, low, mid - 1, x)

else:

return binary_search(arr, mid + 1, high, x)

else:

return -1

list1 = [item for item in input("\nEnter the list of names : ").split()]

search = str(input('\nEnter Name to be searched : '))

list1.sort()

print('\nList : ',list1)

index = binary_search(list1,0,len(list1)-1,search)

if (index == -1):

print('\nElement Not Found')

else:

print('\nElement Found At Index : ',str(index))

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):

for i in range(1, len(arr)):

val = arr[i]

j = i-1

while j >=0 and val < arr[j] :

arr[j+1] = arr[j]

j -= 1

arr[j+1] = val

return arr

item = input('\nEnter Word : ')

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):

for j in range(0, n-i-1):

if arr[j] > arr[j+1] :

arr[j], arr[j+1] = arr[j+1], arr[j]

arr = [int(item) for item in input('\nEnter list of Numbers : ').split()]

print('\nGiven Array is : ',arr)

bubbleSort(arr)

print('\nSorted Array is : ',arr)

OUTPUT:

150200107065 Page 39
Que.22) Implement Quick sort algorithm.

Program: Practical_22.py

def partition(arr, low, high):

i = (low-1)

pivot = arr[high]

for j in range(low, high):

if arr[j] <= pivot:

i = i+1

arr[i], arr[j] = arr[j], arr[i]

arr[i+1], arr[high] = arr[high], arr[i+1]

return (i+1)

def quickSort(arr, low, high):

if len(arr) == 1:

return arr

if low < high:

pi = partition(arr, low, high)

quickSort(arr, low, pi-1)

quickSort(arr, pi+1, high)

arr = [int(item) for item in input('\nEnter list of Numbers : ').split()]

n = len(arr)

print('\nInput List : ',arr)

quickSort(arr, 0, n-1)

print('\nSorted List : ',arr)

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)):

print(i, end = " ")

for j in hashTable[i]:

print("-->", end = " ")

print(j, end = " ")

print()

HashTable = [[] for _ in range(10)]

def Hashing(key):

return key % len(HashTable)

def insert(Hashtable, key, value):

hash_key = Hashing(key)

Hashtable[hash_key].append(value)

insert(HashTable, 12, 'Hardik')

insert(HashTable, 12, 'Nikul')

insert(HashTable, 21, 'Faizan')

insert(HashTable,12,'Sachin')

insert(HashTable, 6, 'Vikky')

insert(HashTable,14,'Dipen')

insert(HashTable, 26, 'John')

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('\nCurrent Working Directory : ',os.getcwd())

print('\nCurrent Directory Content : ')

print(*(os.listdir()),sep='\n')

directory = input('\nEnter Directory Name to be displayed : ')

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

fileName = input('\nEnter file name: ')

numOfLines = 0

with open(fileName, 'r') as f:

for line in f:

numOfLines += 1

print('\nNumber of lines : ',numOfLines)

text = open(fileName,'r').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)

print('\nNumber of Unique Words : ',len(unique))

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 = []

print('\nType exit to stop writing.')

print('\nEnter content of file to be appended in \'python.py\' file : ')

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('\nContent of \'python.py\' file is\n')

with open(fileName,'r') as reader:

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):

result = filter(lambda x:len(x)==5 and x.startswith('m'),data)

return list(result)

# 1. From Console

list1 = []

print('\nType exit to stop writing.')

print('\nEnter string :')

while True:

line = input('')

if line == 'exit':

break

else:

temp = line.split(' ')

for item in temp:

list1.append(item)

print('\nOutput From Console')

print('\nWords Starting with \'m\' and length 5 is : ')

print(getResult(list1))

150200107065 Page 49
# 2. From File

fileName = input('\nEnter File Name : ')

text = open(fileName,'r').read()

text = text.lower()

words = text.split()

words = [word.strip('.,!;()[]') for word in words]

words = [word.replace("'s", '') for word in words]

print('\nOutput From File')

print('\nWords Starting with \'m\' and length 5 is : ')

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'

with open(fileName,'r') as reader:

text = reader.read().splitlines()

finalSet = []

for line in text:

name = line.split(' ')

if(len(name) == 2):

try:

student = datetime.datetime.strptime(name[1],'%m-%d-%Y')

finalSet.append(line)

except ValueError:

pass

print('\nStudent\'s name with DOB(mm-dd-yyyy)')

for item in finalSet:

temp = item.split(' ')

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:

MAX_LEN = int(input('\nEnter Random Password Length : '))

if MAX_LEN > 4:

break

else:

print('\nPassword Length should be greater than 4.Try Again...!!!')

DIGITS = list(string.digits)

LOCASE_CHARACTERS = list(string.ascii_letters)[:26]

UPCASE_CHARACTERS = list(string.ascii_letters)[26:]

SYMBOLS = list(string.punctuation)

COMBINED_LIST = DIGITS + UPCASE_CHARACTERS +


LOCASE_CHARACTERS + SYMBOLS

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

for x in range(MAX_LEN - 4):

temp_pass = temp_pass + random.choice(COMBINED_LIST)

temp_pass_list = array.array('u', temp_pass)

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:

print('\n Invalid Email')

email = input('\nEnter Email to be Checked : ')

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

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: ')

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

from _thread import *

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))

print('Waitiing for a Connection..')

ServerSocket.listen(5)

def threaded_client(connection):

connection.send(str.encode('Welcome to the Server'))

while True:

data = connection.recv(1024)

reply = 'Server Says: ' + data.decode('utf-8')

if not data:

break

connection.sendall(str.encode(reply))

connection.close()

150200107065 Page 57
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()

OUTPUT:

150200107065 Page 58
Que.32) Write a program to plot different types of graphs using PyPlot.

Program: Practical_32.py

# py

import matplotlib.pyplot as plt

import numpy as np

# 1. One Line in one Plane

x = [1,2,3]

y = [2,4,1]

plt.plot(x, y)

plt.xlabel('Time')

plt.ylabel('Distance')

plt.title('Speed')

plt.show()

# 2. Two Line in one plane

x1 = [1,2,3]

y1 = [2,4,1]

plt.plot(x1, y1, label = "line 1")

x2 = [1,2,3]

y2 = [4,1,3]

plt.plot(x2, y2, label = "line 2")

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]

height = [10, 24, 36, 40, 5]

tick_label = ['one', 'two', 'three', 'four', 'five']

plt.bar(left, height, tick_label = tick_label,

width = 0.8, color = ['blue', 'green'])

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]

range = (0, 100)

bins = 10

plt.hist(ages, bins, range, color = 'blue',

histtype = 'bar', rwidth = 0.8)

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.scatter(x, y, label= "stars", color= "blue",

marker= "*", s=30)

plt.xlabel('x - axis')

plt.ylabel('y - axis')

plt.title('Scatter Plot')

plt.legend()

plt.show()

# 6. Pie chart

activities = ['Forest', 'Land', 'River', 'Agriculture']

slices = [4, 5, 9, 4]

colors = ['r', 'y', 'g', 'b']

plt.pie(slices, labels = activities, colors=colors,

startangle=90, shadow = True, explode = (0, 0, 0.1, 0),

radius = 1.2, autopct = '%1.1f%%')

plt.title('Pie Chart')

plt.show()

# 7. Curves

x = np.arange(0, 2*(np.pi), 0.1)

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()):

result += chr((ord(char) + s-65) % 26 + 65)

else:

result += chr((ord(char) + s - 97) % 26 + 97)

return result

text = input('\nEnter Plain Text : ')

shift = int(input('\nEnter Shift Pattern : '))

print('\nPlain Text : ' + text)

print('Shift pattern : ' + str(shift))

print('Cipher Text : ' + encrypt(text,shift))

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()

for i in range (3):

triangle.forward(50)

triangle.left(120)

# 2. A square

square =turtle.Turtle()

square.up()

square.forward(70)

square.down()

for i in range (4):

square.forward(50)

square.left(90)

# 3. Hexgon

150200107065 Page 65
hex =turtle.Turtle()

hex.up()

hex.forward(-70)

hex.down()

for i in range (6):

hex.forward(30)

hex.left(60)

# 4. An Octagon

oct =turtle.Turtle()

oct.up()

oct.forward(-170)

oct.down()

for i in range (8):

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

from tkinter import *

root = Tk(className="Pratical-35")

root.geometry("500x500")

def message():

w = Label(root, text = "Hello Hardik")

w.pack()

button = Button(root, text = "Click Me!", command = message)

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

from tkinter import *

from random import choice

root = Tk()

root.geometry("500x500")

root.title("GTU Pyhton Pratical-36")

canvas=Canvas(root, height=500, width=500)

buttonRed = Button(root, text = "Red", anchor = W,


command=lambda:canvas.configure(bg="red"))

buttonRed.configure(width=10,activebackground="red",relief=FLAT)

buttonBlue = Button(root, text = "Blue", anchor = W,


command=lambda:canvas.configure(bg="blue"))

buttonBlue.configure(width=10,activebackground="blue",relief=FLAT)

buttonGreen = Button(root, text = "Green", anchor = W,


command=lambda:canvas.configure(bg="green"))

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

You might also like