GYAN GANGA INSTITUTE OF
TECHNOLOGY & SCIENCES
Python Lab [CS-506]
PRACTICAL FILE
Submitted By Submitted To
Name: Name: Prof. Ankita Chaturvedi
Enrolment No: Designation: Asst Professor
Python Lab by Ankita Chaturvedi
Index
Sl. No. List of Programs Date Remark Sign
1 To write a Python program to find GCD of two numbers.
2 To write a Python Program to find the square root of a number by
Newton’s Method.
3 To write a Python program to find the exponentiation of a number.
4 To write a Python Program to find the maximum from a list of numbers.
5 To write a Python Program to perform Linear Search
6 To write a Python Program to perform binary search.
7 To write a Python Program to perform selection sort.
8 To write a Python Program to perform insertion sort.
9 To write a Python Program to perform Merge sort.
10 To write a Python program to find first n prime numbers.
11 To write a Python program to multiply matrices.
12 To write a Python program for command line arguments.
13 To write a Python program to find the most frequent words in a text
read from a file.
14 To write a Python program to simulate elliptical orbits in Pygame.
15 To write a Python program to bouncing ball in Pygame.
Python Lab by Ankita Chaturvedi
PYTHON PROGRAMMING LAB
CS-506
SEMESTER– V
Syllabus
1) Write a Python program to find GCD oftwo numbers.
2) Write a Python Program to find the square root of a number by Newton’s Method
3) Write a Python program to find theexponentiation ofanumber.
4) Write a Python Program to find the maximum from a list of numbers.
5) Write a Python Program to perform Linear Search
6) W rite a Python Program to perform Binary Search
7) Write a Python Program to perform selection sort.
8) Write a Python Program to perform insertion sort.
9) Write a Python Program to perform Merge sort.
10)Write a Python program to find first n primenumbers.
11)Write a Python program to multiply matrices.
12) To write a Python program for command line arguments.
13) To write a Python program to find the most frequent words in a text read from a file.
14) To write a Python program to simulate elliptical orbits in Pygame.
15)To write a Python program to bouncing ball in Pygame.
Python Lab by Ankita Chaturvedi
Program1: Write a Python program to find GCD of two numbers.
Aim:
To write aPython program to find GCD oftwo numbers.
Algorithm:
1. Defineafunction named compute GCD()
2. Find thesmallest amongthe two inputs xandy
3. Perform the following step tillsmaller+1
Check if ((x% i==0)and (y%i ==0)), then assign GCD=i
4. Print thevalue ofgcd
Program:
defcomputeGCD(x, y):
if x > y:
smaller = y
else:
smaller = x
fori in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
returngcd
computeGCD(54, 24)
Sample Output:
$[Link]
('TheGCD. of', 54,'and',24, 'is', 6)
Python Lab by Ankita Chaturvedi
Program2:Write a Python Program to find the square root of a number by
Newton’s Method
Aim:
To write aPython Program to find thesquare rootofanumberbyNewton’sMethod.
Algorithm:
1. Define a function named newtonSqrt().
[Link] approx as 0.5*n and better as 0.5*(approx.+n/approx.)
3. Use a while loop with a condition better!=approxto perform the following,
i. Set approx.=better
ii. Better=0.5*(approx.+n/approx.)
4. Print the value of approx..
Program:
defnewtonSqrt(n):
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx=better
better = 0.5 * (approx + n/approx)
returnapprox
newtonSqrt(100)
Sample Output:
26
Python Lab by Ankita Chaturvedi
Program3: Write aPython programto find theexponentiation ofanumber.
Aim:
To write a Python program to find the exponentiation of anumber.
Algorithm:
1. Define a function named power()
2. Read the values of base and exp
3. Use ‘if’to check if exp is equal to 1 ornot
i. if exp is equal to 1, then return base
[Link] exp is not equal to 1,then return (base*power(base,exp-1))
4. Print the result.
Program:
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Sample Output:
Enter base: 7
Enter exponential value: 2
Result:49
Python Lab by Ankita Chaturvedi
Program 4: Write a Python Program to find the maximum from a list of numbers.
Aim:
To write aPython Program to find themaximum from a list of numbers.
Algorithm:
1. Create anemptylist named l
2. Read the value of n
3. Read the elements of thelistuntil n
4. Assign l[0]as maxno
[Link] l[i]>maxno then set maxno=l[i]
[Link] iby1
7. Repeat steps 5-6 until i<n
8. Print thevalue ofmaximum number
Program:
l=[]
n=int(input("enter theupper limit"))
foriin range(0,n):
a=int(input("enterthenumbers"))
[Link](a)
maxno=l[0]
foriin range(0,len(l)):
if l[i]>maxno:
maxno=l[i]
print("Themaximum numberis %d"%maxno)
Sample Output: Enterthe upper limit 3
Enter thenumbers 6
Enter thenumbers 9
Enter thenumbers 90
Themaximum number is 90
Python Lab by Ankita Chaturvedi
Program5: Write aPython ProgramtoperformLinear Search
Aim:
To write aPython Program to performLinear Search
Algorithm:
1. Read n elements into thelist
2. Read the element to besearched
[Link] alist[pos]==item, then print theposition ofthe item
4. else increment theposition and repeat step 3 untilpos reaches the length of the list
Program:
elements = [5, 7, 10, 12, 15]
print("list of elements is", elements)
x=int(input("enterelementto search:"))
i = flag=0
whilei<len(elements):
if elements[i]==x:
flag =1
break
i = i +1
ifflag==1:
print("element found at position:", i + 1)
else:
print("element notfound")
SampleOutput:
$[Link]
(list of items is: [5, 7, 10, 12, 15])
enteritem to search:7 (item
found at position:, 2)
Python Lab by Ankita Chaturvedi
Program 6: Write a Python Program to perform Binary Search
Aim:
To write a Python Program to perform binary search.
Algorithm:
1. Read the search element
2. Find themiddle element in the sorted list
3. Comparethe searchelement with the middle element
i. if both arematching, printelement found
ii. else then check if thesearchelement is smallerorlarger than the middleelement
[Link] thesearchelement is smaller than the middle element, then repeat steps 2 and 3 for the
left sublistof themiddle element
[Link] thesearchelement is larger than themiddleelement, then repeat steps2 and 3 forthe
right sublist of the middle element
6. Repeat theprocess untilthe searchelement if found in thelist
[Link] element is not found, loop terminates
Program:
# Pythoncodeto implement iterativeBinarySearch.
#Itreturns location ofxin givenarrayarr
# if present, elsereturns-1
defbinarySearch(arr, l, r, x):
while l <= r:
mid =l + (r -l)/2;
# Check if xis present at mid
if arr[mid]==x:
return mid
#If xis greater, ignoreleft half
elifarr[mid]<x:
l = mid + 1
#If xis smaller, ignoreright half
else:
r =mid -1
#Ifwereach here, then the element
# was not present
return -1
# Test array
arr=[2, 3, 4, 10, 40 ]
x=4
# Function call
result=binarySearch(arr, 0, len(arr)-1, x)
ifresult!= -1:
Python Lab by Ankita Chaturvedi
print"Element is present at index% d"% result
else: else
print"Element is not present in array"
Sample Output:
$[Link]
Element is present at index 2
Python Lab by Ankita Chaturvedi
Program7: Write a Python Program to perform selection sort.
Aim:
To write aPython Program to perform selection sort.
Algorithm:
1. Create afunction named selectionsort
[Link]=0
[Link] alist[location]>alist[pos]then perform the followingtilli+1,
4. Set pos=location
5. Swap alist[i]and alist[pos]
6. Print thesorted list
Program:
defselectionSort(alist):
foriin range(len(alist)-1,0,-1):
pos=0
forlocation in range(1,i+1):
ifalist[location]>alist[pos]:
pos=location
temp =alist[i]
alist[i]=alist[pos]
alist[pos]=temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
SampleOutput:
$[Link]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
Python Lab by Ankita Chaturvedi
Program8: Write aPython Programtoperforminsertionsort.
Aim:
To write aPython Program to perform insertion sort.
Algorithm:
1. Create afunction named insertionsort
[Link]=alist[index]and position=index
3. while position>0 and alist[position-1]>currentvalue, perform the followingtilllen(alist)
4. alist[position]=alist[position-1]
5. position =position-1
6. alist[position]=currentvalue
7. Print thesorted list
Program:
definsertionSort(alist):
forindexin range(1,len(alist)):
currentvalue =alist[index]
position =index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position =position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
Sample Output:
$python [Link]
[20, 54, 54, 54, 54, 54, 93, 93, 93]
Python Lab by Ankita Chaturvedi
Program9: Write aPython ProgramtoperformMerge sort.
Aim:
To write aPython Program to perform Mergesort.
Algorithm:
1. Create afunction named mergesort
2. Find themid of thelist
3. Assign lefthalf =alist[:mid]and righthalf=alist[mid:]
[Link]=j=k=0
5. whilei<len(lefthalf)and j <len(righthalf), perform the following if
lefthalf[i]<righthalf[j]:
alist[k]=lefthalf[i]
Increment i
else
alist[k]=righthalf[j]
Increment j
Increment k
6. whilei<len(lefthalf),perform thefollowing
alist[k]=lefthalf[i]
Increment i
Increment k
7. while j <len(righthalf), perform thefollowing
alist[k]=righthalf[j]
Increment j
Increment k
8. Print thesorted list
Program:
# Python programforimplementation of MergeSort
# Merges two subarraysofarr[].
# First subarrayis arr[l..m]
# Second subarrayis arr[m+1..r]
def merge(arr, l, m, r):
n1 =m -l + 1
n2 = r-m
# createtemp arrays
L=[0]* (n1) R
=[0]* (n2)
# Copydata to temp arraysL[]and R[]
Python Lab by Ankita Chaturvedi
L[i]=arr[l + i]
forj in range(0 , n2):
R[j]=arr[m + 1 +j]
# Mergethe temparraysback into arr[l..r]
i = 0 #Initial indexof first subarray
j = 0 #Initial indexof secondsubarray k
=l #Initial indexof mergedsubarray
whilei<n1 and j < n2 :
ifL[i]<=R[j]:
arr[k]=L[i] i
+=1
else:
arr[k]=R[j]
j +=1
k +=1
# Copythe remaining elements ofL[], if there
# areany
while i<n1:
arr[k]=L[i]
i +=1
k +=1
# Copythe remaining elements of R[],if there
# areany
while j <n2:
arr[k]=R[j]
j +=1
k +=1
# lis forleft indexand r is right indexof the
# sub-arrayof arrto be sorted
defmergeSort(arr,l,r):
if l < r:
# Sameas (l+r)/2, but avoids overflow for
# largel and h
m = (l+(r-1))/2
# Sort first andsecond halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver codeto test above
arr=[12, 11, 13, 5, 6, 7]
n =len(arr)
print("Givenarrayis")
Python Lab by Ankita Chaturvedi
foriin range(n):
print("%d"%arr[i]),
mergeSort(arr,0,n-1)
print("\n\nSortedarrayis")
foriin range(n):
print("%d"%arr[i]),
Sample Output:
$python [Link]
Given arrayis
12 11 13 5 6 7
Sorted arrayis
5 6 7 11 12 13
Python Lab by Ankita Chaturvedi
Program10: WriteaPython programto find first nprimenumbers.
Aim:
To write aPython program to find first n primenumbers.
Algorithm:
1. Read the value of n
2. fornumin range(0,n + 1), perform the following
3. ifnum%i is 0 then break
else printthe value ofnum
4. Repeat step 3 for i in range(2,num)
Program:
n =int(input("Enter theupper limit: "))
print("Primenumbersare")
fornumin range(0,n +1):
# primenumbers aregreater than 1
if num>1:
foriin range(2,num):
if(num % i) ==0:
break
else:
print(num)
Sample Output:
$python [Link]
Enter theupper limit:20
Primenumbers are
2
3
5
7
11
13
17
19
Python Lab by Ankita Chaturvedi
Program11: Write a Python programto multiplymatrices.
Aim:
Algorithm:
To write a Python program to multiply matrices.
Python Lab by Ankita Chaturvedi
1. Definetwo matrices Xand Y
2. Create aresultant matrixnamed ‘result’
3. foriin range(len(X)):
i. forj in range(len(Y[0])):
a) fork in range(len(Y))
b)result[i][j]+=X[i][k]* Y[k][j]
4. forrin result, print thevalue ofr
Program:
X =[[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y =[[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
foriin range(len(X)):
forj in range(len(Y[0])):
fork in range(len(Y)):
result[i][j]+=X[i][k]* Y[k][j]
forrin result:
print(r)
Sample Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Python Lab by Ankita Chaturvedi
To write a Python program for command line arguments.
What is [Link]?
[Link] is the list of commandline arguments passed to the Python program. argv represents all the
items that come along via the command line input, it's basically an array holding the command line
arguments of our program. Don't forget that the counting starts at zero (0) not one (1).
import sys
for x in [Link]:
print "Argument: ", x
Output:
>python [Link]
Argument: [Link]
>python [Link] hello
Argument: [Link]
Argument: hello
>python [Link] hello world
Argument: [Link]
Argument: hello
Argument: world
Python Lab by Ankita Chaturvedi
To write a Python program to find the most frequent words in a text read from a file.
In this program, we need to find the most repeated word present in given text file. This can be
done by opening a file in read mode using file pointer. Read the file line by line. Split a line at
a time and store in an array. Iterate through the array and find the frequency of each word and
compare the frequency with maxcount. If frequency is greater than maxcount then store the
frequency in maxcount and corresponding word that in variable word. The content of [Link]
file used in the program is shown below.
1. [Link]
Algorithm
1. Variable maxCount will store the count of most repeated word.
2. Open a file in read mode using file pointer.
3. Read a line from file. Convert each line into lowercase and remove the punctuation
marks.
4. Split the line into words and store it in an array.
5. Use two loops to iterate through the array. Outer loop will select a word which needs to
be count. Inner loop will match the selected word with rest of the array. If match found,
increment count by 1.
6. If count is greater than maxCount then, store value of count in maxCount and
corresponding word in variable word.
7. At the end, maxCount will hold the maximum count and variable word will hold most
repeated word.
count = 0;
word = "";
maxCount = 0;
words = [];
#Opens a file in read mode
file = open("[Link]", "r")
#Gets each line till end of file is reached
for line in file:
#Splits each line into words
string = [Link]().replace(',','').replace('.','').split(" ");
#Adding all words generated in previous step into words
for s in string:
[Link](s);
Python Lab by Ankita Chaturvedi
#Determine the most repeated word in a file
fori in range(0, len(words)):
count = 1;
#Count each word in the file and store it in variable count
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;
#IfmaxCount is less than count then store value of count in maxCount
#and corresponding word to variable word
if(count >maxCount):
maxCount = count;
word = words[i];
print("Most repeated word: " + word);
[Link]();
Output:
Most repeated word: computer
Python Lab by Ankita Chaturvedi
To write a Python program to simulate elliptical orbits in Pygame.
importpygame
import math
import sys
[Link]()
screen = [Link].set_mode((600, 300))
[Link].set_caption("Elliptical orbit")
clock = [Link]()
while(True):
for event in [Link]():
[Link] == [Link]:
[Link]()
xRadius = 250
yRadius = 100
for degree in range(0,360,10):
x1 = int([Link](degree * 2 * [Link] / 360) * xRadius) + 300
y1 = int([Link](degree * 2 * [Link] / 360) * yRadius) + 150
[Link]((0, 0, 0))
[Link](screen, (255, 0, 0), [300, 150], 35)
[Link](screen, (255, 255, 255), [50, 50, 500, 200], 1)
[Link](screen, (0, 0, 255), [x1, y1], 15)
[Link]()
[Link](5)
Python Lab by Ankita Chaturvedi
To write a Python program to bouncing ball in Pygame.
import sys, pygame
[Link]()
size = width, height = 700, 300
speed = [1, 1]
background = 255, 255, 255
screen = [Link].set_mode(size)
[Link].set_caption("Bouncing ball")
ball = [Link]("[Link]")
ballrect = ball.get_rect()
while 1:
for event in [Link]():
[Link] == [Link]: [Link]()
ballrect = [Link](speed)
[Link]< 0 or [Link]> width:
speed[0] = -speed[0]
[Link]< 0 or [Link]> height:
speed[1] = -speed[1]
[Link](background)
[Link](ball, ballrect)
[Link]()
Python Lab by Ankita Chaturvedi
VIVAVOCEQUESTIONS
1. What it thesyntaxof print function?
2. What is the usageof input function?
3. Defineavariable.
4. What is typeconversion?
5. Mention the data typesin Python
6. What arethe attributesof the complexdatatype?
7. Mention a fewescapesequences.
8. Define anexpression
9. What is the usageof ** operator in Python?
10. Givethe syntaxof if else statement.
11. Givethe syntaxof forstatement.
12. Howis rangefunction used in for?
13. Givethe syntaxof while statement.
14. What aremultiwayif statements?
15. Howis random numbersgenerated?
16. Defineafunction.
17. Givethe syntaxof function.
18. What arethe types ofarguments in function.?
19. What is a recursive function?
20. What are anonymousfunctions?
21. What aredefaultarguments?
22. What arevariable length arguments?
23. What arekeyword arguments?
24. Mention theuse of map().
25. Mention theuse of filter().
26. Mention theuse of reduce().
27. Defineastring.
28. Howis stringslicing done?
29. What is the usageofrepetition operator?
30. Howis stringconcatenation doneusing+operator>
31. Mention somestring methods
Python Lab by Ankita Chaturvedi
32. Howis length ofastringfound?
Python Lab by Ankita Chaturvedi
33. Howis a string converted to its upper case?
34. `Differentiate isalpha() and isdigit().
35. What is the useof split()?
36. Defineafile.
37. Givethe syntaxforopening a file.
38. Givethe syntaxfor closinga file.
39. Howis readingoffile done?
40. Howis writingoffiledone?
41. What is a list?
[Link] aremutable-Justify.
43. Howis a list created?
44. How canalist be sorted?
45. How are elements appended to thelist?
46. Howis insert()usedin list?
47. What is the usageofpop()in list?
48. Defineatuple.
49. Aretuples mutable orimmutable?
50. Mention theuse of return statement.
51. What is a Boolean function?
52. Howis main function defined?
53. What is a dictionary?
54. How aretuples created?
55. Howis a dictionarycreated?
56. Howto print the keysof adictionary?
57. Howto print the values ofadictionary?
58. Howis del statementused?
59. Can tuple elements bedeleted?
60. What is Python interpreter?
61. Whyis Python calledan interpreted language?
62. Mention some features of Python
63. What is PythonIDLE?
64. Mention some rules fornaming an identifier inPython.
65. Givepoints about Python Numbers.
Python Lab by Ankita Chaturvedi
66. What is bool datatype?
67. Give examples of mathematical functions.
68. What is stringformattingoperator?
69. Mention about membership operators inPython.
70. Howis expression evaluated in Python?
71. What arethe loop control statements in Python?
72. What is the useof break statement?
73. What is the useof continuestatement?
74. What is the useof pass statement?
75. What is assert statement?
76. Differentiate fruitfulfunction s and void functions.
77. What are required arguments ?
78. Differentiate pass byvalue and pass byreference.
79. Mention few advantages of function.
80. Howis lambda function used?
81. What is a local variable?
82. What areglobal variables?
83. What arePython decorators?
84. Arestrings mutable or immutable?
85. What is join()?
86. What is replace() method?
87. What is list comprehension?
88. Definemultidimensional list.
89. Howto create lists usingrange()?
90. What is swapcase()method?
91. What is linear search?
92. Howis binarysearchdone?
93. Howis mergesort performed?
94. What is sorting?
95. Howis insertion sort done?
96. Howis selection sortdone?
97. What are command line arguments?
98. Name some built in functions with dictionary.
Python Lab by Ankita Chaturvedi
99. What is an exception?
100. Howis exception handled in python?
******************************* TheEnd***********************************
Python Lab by Ankita Chaturvedi