python lab manual UPDATED AUG 27.8.24 (1) (1)
python lab manual UPDATED AUG 27.8.24 (1) (1)
Page
Date Name of the Experiment Mark Sign
No. No.
Start
Stop
Result:
Thus the flowchart for solving electricity billing problem is designed and it is
verified.
Ex. No. : 1.b Retail Shop Billing Date:
Result:
Thus the flowchart for solving retail shop billing problem is designed and it
is verified.
Ex. No. : 1.c Sine Series Date:
Read Degree
sine(deg)
cosine(deg)
Result:
Thus the flowchart for solving sine series problem is designed and it is
verified.
Output :
Ex. No. : 2 EXCHANGE THE VALUES OF TWO VARIABLES Date:
Aim:
To write a Python program to exchange the values of two variables.
Algorithm:
1. Read the values of two values x and y
2. Use any one method
a. Method 1: Using third variable (Temporary)
b. Method 2: WithoutUsing third variable (Temporary)
c. Method 3: Using comma operator
3. Print the swapped values
Program:
Method 1: Using third variable (Temporary)
x =10
y =50
temp =x
x =y
y =temp
print("Value of x:", x)
print("Value of y:", y)
Method 2: WithoutUsing third variable (Temporary)
x =10
y =50
x =x +y
y =x -y
x =x -y
print("Value of x:", x)
print("Value of y:", y)
Method 3: Using comma operator
x =10
y =50
x, y =y, x
print("Value of x:", x)
print("Value of y:", y)
Result:
Thus the Python program to exchange the values of two variables is executed
successfully and the output is verified.
Output :
Ex. No. : 3 CIRCULATE THE VALUES OF N VARIABLES Date:
Aim:
To write a Python program to circulate the values of n variables.
Algorithm:
1. Read the value of no. of items
2. Initialize a list variable with null value
3. Use for loop to read the items and append the items in list
4. Use for loop and pop() funtion to circulate the items and update the
items in the list
5. Print the list after finishing the circulation
Program:
no_of_terms = int(input("Enter number of values : "))
#Read values
list1 = []
for val in range(0,no_of_terms,1):
ele = int(input("Enter integer : "))
list1.append(ele)
#Circulate and display values
print("Circulating the elements of list ", list1)
for val in range(0,no_of_terms,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
Result:
Thus the Python program to circulate the values of n variablesis executed
successfully and the output is verified.
Output :
Ex. No. : 4 CALCULATE DISTANCE BETWEEN TWO POINTS Date:
Aim:
To write a Python program to find the distance between two points.
Algorithm:
1. Read the values of two coordinates (x1,x2) and (y1,y2)
𝑦1)2
3. Print the calculated distance value
Program:
x1=int(input("Enter x1 : "))
x2=int(input("Enter x2 : "))
y1=int(input("Enter y1 :
")) y2=int(input("Enter y2
: "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("Distance between",(x1,x2),"and",(y1,y2),"is: ",result)
Result:
Thus the Python program to find the distance between two points is executed
successfully and the output is verified.
Output :
Ex. No. : 5 COMPUTE THE GCD OF TWO NUMBERS Date:
Aim:
To write a Python program to find GCD of two numbers.
Algorithm:
4. Define a function named computeGCD()
5. Find the smallest among the two inputs x and y
6. Perform the following step till smaller+1
i. Check if ((x % i == 0) and (y % i == 0)), then assign GCD=i
7. Print the value of gcd
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
num1 = 54
num2 = 24
# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))
Result:
Thus the Python program to compute GCD of two numbers is executed
successfully and the output is verified.
Output:
FIND THE SQUARE ROOT OF A NUMBER
Ex. No. : 6 Date:
(NEWTON’S METHOD)
Aim:
To write a Python Program to find the square root of a number by Newton’s
Method.
Algorithm:
1. Define a function named newtonSqrt().
2. Initialize approx as 0.5*n and better as 0.5*(approx.+n/approx.)
3. Use a while loop with a condition better!=approx to perform the following,
i. Set approx.=better
ii. Better=0.5*(approx.+n/approx.)
4. Print the value of approx
Program:
def newton_sqrt(n, tolerance=1e-10, max_iterations=1000):
"""Calculate the square root of a number using Newton's method."""
if n < 0:
raise ValueError("Cannot compute the square root of a negative number")
# Initial guess
guess = n
iteration = 0
return guess
Result:
Thus the Python program for finding the square root of a given number by
Output:
Aim:
To write a Python program to find the exponentiation of a number.
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 or not
i. if exp is equal to 1, then return base
ii. if exp is not equal to 1, then return (base*power(base,exp-1))
4. Print the result
Program:
# Get user input for base and exponent
base = float(input("Enter the base: "))
exponent = float(input("Enter the exponent: "))
# Calculate exponentiation using the ** operator
result = base ** exponent
# Print the result
print(f"{base} raised to the power of {exponent} is {result}.")
Result:
Thus the Python program to find the exponentiation of a number is executed
successfully and the output is verified.
Output:
Ex. No. : 8 CHECK A NUMBER IS ODD OR EVEN Date:
Aim:
Algorithm:
Program:
Result:
Thus the Python program to check if a number is odd or even is executed
successfully and the output is verified.
Output:
Ex. No. : 9 CALCULATE THE AVERAGE OF NUMBERS IN A LIST Date:
Aim:
Algorithm:
1. User must first enter the number of elements which is stored in the
variable n.
2. The value of I ranges from 0 to the number of elements and is
incremented each time after the body of the loop is executed.
3. Then, the element that the user enters is stored in the variable element.
4. a.append(elem) appends the element to the list.
5. Now the value of i is incremented to 2.
6. The new value entered by the user for the next loop iteration is now
stored in elem which is appended to the list.
7. The loop runs till the value of i reaches n.
8. sum(a) gives the total sum of all the elements in the list and dividing it
by the total number of elements gives the average of elements in the list.
9. round(avg,2) rounds the average upto 2 decimal places.
10. Then the average is printed after rounding.
Program:
Result:
Thus the Python program to calculate the average of numbers in a list is
executed successfully and the output is verified.
Output:
Ex. No. : 10 DISPLAY THE GRADE OF A STUDENT Date:
Aim:
Algorithm:
Program:
Result:
Thus the Python program to display the grade of a student is executed
successfully and the output is verified.
Output:
Aim:
Algorithm:
Program:
def sum_of_digits(number):
# Take the absolute value to handle negative numbers
number = abs(number)
total_sum = 0
return total_sum
Aim:
Algorithm:
Program:
a=[1,2,3,4,5]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:", a[n-1])
Result:
Thus the Python program to find maximum number in a list is executed
successfully and the output is verified.
Output:
Ex. No. : 13 CHECK THE NUMBER IS PALINDROME OR NOT Date:
Aim:
Algorithm:
1. User must first enter the value of the integer and store it in a variable.
2. The value of the integer is then stored in another temporary variable.
3. The while loop is used and the last digit of the number is obtained by
using the modulus operator.
4. The last digit is then stored at the one’s place, second last at the ten’s
place and so on.
5. The last digit is then removed by truly dividing the number with 10.
6. This loop terminates when the value of the number is 0.
7. The reverse of the number is then compared with the integer value stored
in the temporary variable.
8. If both are equal, the number is a palindrome.
9. If both aren’t equal, the number isn’t a palindrome.
10. The final result is then printed.
Program:
def is_palindrome(num):
original = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
return original == reversed_num
n = int(input("Enter a number: "))
if is_palindrome(n):
print("The number is a palindrome!")
else:
print("The number is not a palindrome.")
Result:
Thus the Python program to check the number is palindrome or not is
Output:
Algorithm:
Program:
Result:
Thus the Python program to print table of a number is executed successfully
and the output is verified.
Aim:
Output:
Ex. No. : 15 PASCAL'S TRIANGLE Date:
Algorithm:
1. User must enter the number of rows that the Pascal’s triangle should
have.
2. The for loop is used to append sub-lists into an empty list defined earlier.
3. Then 1 is appended into all the sub-lists.
4. The for loop is used to determine the value of the number inside the
triangle which is the sum of the two numbers above it.
5. The other for loop is used to print the Pascal’s triangle according to the
format.
Program:
Result:
Thus the Python program to generate pascal’s triangle is executed
successfully and the output is verified.
Aim:
Output:
Algorithm:
1. User must enter the number of natural numbers to find the sum of.
2. The sum variable is initialized to 0.
3. The while loop is used to find the sum of natural numbers and the
number is decremented for each iteration.
4. The numbers are added to the sum variable and this continues till the
value of the variable is greater than 0.
5. When the value of the variable becomes lesser than 0, the total sum of N
natural numbers is printed.
Program:
Result:
Thus the Python program to calculate sum of n natural numbers is executed
successfully and the output is verified.
EXP 17: To perform matrix addition and subtraction
Algorithm:
# Addition
for i in range(len(X)):
for j in range(len(X[0])):
resultA[i][j] = X[i][j] + Y[i][j]
# Subtraction
for i in range(len(X)):
for j in range(len(X[0])):
resultS[i][j] = X[i][j] - Y[i][j]
print("\nSubtraction Result:")
for r in resultS:
print(r)
Result:
Thus the Python program for matrix addition and subtraction is executed
successfully and the output is verified.
Output:
Ex. No. : 18 COUNT THE NUMBER OF VOWELS Date:
Algorithm:
Program:
Result:
Thus the Python program to count the number of vovels is executed
successfully and the output is verified.
Output:
Aim:
Ex. No. : 19 CHECK ARMSTRONG NUMBER Date:
Algorithm:
1. Start
2. Read a value in a variable ‘num’
3. Initialize zero to the variable ‘sum’
4. Transfer num value to a temp variable.
5. Check a condition temp > 0, if it is greater than 0
a. digit = temp % 10]
b. sum += digit ** 3
c. temp //= 10
6. Then check a condition num = sum, if it is print as it’s a Armstrong
number
7. Else print as not an Armstrong number
8. Stop the process.
Program:
num = int(input("Enter a number: "))
sum = 0
temp = num
if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
Result:
Thus the Python program to check armstrong number is executed
successfully and the output is verified.
Output
Aim:
Ex. No. : 20 CONVERT CELSIUS TO FAHRENHEIT Date:
Algorithm:
1. Start.
2. Read the celsius value in a variable ‘celsius’.
3. Perform an operation fahrenheit=(celsius * 1.8)+ 32
4. Print the Fahrenheit value.
5. Stop the process.
Program:
celsius = float(input("Enter the Celsius value: "))
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius,
fahrenheit))
Result:
Thus the Python program to convert celsius to fahrenheitis
executed successfully and the output is verified.
Output:
Aim:
Exp no:21 To perform Linear search
Algorithm:
1. Read n elements into the list
2. Read the element to be searched
3. If alist[pos]==item, then print the position of the item
4. Else increment the position and repeat step 3 until pos reaches the
length of the list
Program:
def search(alist, item):
pos = 0
found = False
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
print("Element found at position", pos)
else:
if alist[pos] > item:
stop = True
pos += 1
return found
a = []
Result:
Thus the Python Program to perform linear search is executed successfully
and the output is verified.
Aim:
Output:
Exp22: To perform binary search
Algorithm:
1. Read the search element
2. Find the middle element in the sorted list
3. Compare the search element with the middle element
i. if both are matching, print element found
ii. else then check if the search element is smaller or larger than the
middle element
4. If the search element is smaller than the middle element, then repeat
steps 2 and 3 for the
5. left sublist of the middle element
6. If the search element is larger than the middle element, then repeat
steps 2 and 3 for the
7. right sublist of the middle element
8. Repeat the process until the search element if found in the list
9. If element is not found, loop terminates
Program:
def bsearch(alist, item):
first = 0
last = len(alist) - 1
found = False
return found
a = []
n = int(input("Enter upper limit: "))
for i in range(n):
e = int(input("Enter an element: "))
a.append(e)
Result:
Thus the Python Program to perform binary search is executed successfully
and the output is verified
Output:
Ex. No. : 23 SELECTION SORT Date:
`
Aim:
To write a Python Program to perform selection sort.
Algorithm:
1. Create a function named selectionsort
2. Initialisepos=0
3. If alist[location]>alist[pos] then perform the following till i+1,
4. Set pos=location
5. Swap alist[i] and alist[pos]
6. Print the sorted list
Program:
def selectionSort(alist):
for i in range(len(alist) - 1, 0, -1):
pos = 0
for location in range(1, i + 1):
if alist[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)
Result:
Thus the Python Program to perform selection sort is successfully executed
and the output is verified.
Output:
Ex. No. : 24 INSERTION SORT Date:
Aim:
To write a Python Program to perform insertion sort.
Algorithm:
1. Create a function named insertionsort
2. Initialisecurrentvalue=alist[index] and position=index
3. while position>0 and alist[position-1]>currentvalue, perform the
following till len(alist)
4. alist[position]=alist[position-1]
5. position = position-1
6. alist[position]=currentvalue
7. Print the sorted list
Program:
def insertionSort(alist):
for index in range(1, len(alist)):
currentvalue = alist[index]
position = index
alist[position] = currentvalue
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insertionSort(alist)
print(alist)
Result:
Thus the Python program to perform insertion sort is successfully executed
and the output is verified.
Exp no:25 Merge Sort
Algorithm:
1. Create a function named mergesort
2. Find the mid of the list
3. Assign lefthalf = alist[:mid] and righthalf = alist[mid:]
4. Initialisei=j=k=0
5. while i<len(lefthalf) and j <len(righthalf), perform the following
iflefthalf[i] <righthalf[j]:
alist[k]=lefthalf[i]
Increment i
else
alist[k]=righthalf[j]
Increment j
Increment k
6. while i<len(lefthalf),perform the following
alist[k]=lefthalf[i]
Increment i
Increment k
7. while j <len(righthalf), perform the following
alist[k]=righthalf[j]
Increment j
Increment k
8. Print the sorted list
Program:
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
mergeSort(alist)
print(alist)
Aim:
Result:
Thus the Python program to perform merge sort is successfully executed and
the output is verified.
Output:
Algorithm:
1. Read the value of n
2. for num in range(0,n + 1), perform the following
3. if num%i is 0 then break
else print the value of num
4. Repeat step 3 for i in range(2,num)
Program:
n = int(input("Enter the upper limit: "))
print("Prime numbers are:")
Result:
Thus the Python Program to find the first n prime numbers is executed
successfully and the output is verified.
Output:
Algorithm:
1. Define two matrices X and Y
2. Create a resultant matrix named ‘result’
3. for i in range(len(X)):
a) for j in range(len(Y[0])):
1. for k in range(len(Y))
2. result[i][j] += X[i][k] * Y[k][j]
4. for r in result, print the value of r
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:
Thus the Python program to multiply matrices is executed successfully and
the output is verified.
Output:
Ex. No. : 28 COMMAND LINE ARGUMENTS(WORD COUNT) Date:
To write a Python program to find word count using command line arguments.
Algorithm:
1. Add arguments to find the words and lines
2. Add the filename as argument
3. Parse the arguments to get the values
4. Format and print the words and lines
Program:
parser=argparse.ArgumentParser()
parser.add_argument('--words','-w',action='store_true')
parser.add_argument('--lines','-l',action='store_true')
parser.add_argument('filename')
args=parser.parse_args()
ifargs.words:
print("words {}".format(print_words(args.filename))
elifargs.lines:
print("lines {}".format(print_lines(args.filename))
else:
print ("words {}".format(print_words(args.filename))
print("lines {}".format(print_lines(args.filename))
Result:
Thus the Python program for command line arguments is executed
successfully and the output is verified.
Aim:
Output: FINDING MOST FREQUENT WORDS IN A TEXT
Ex. No. : 29 Date:
READ FROM A FILE
To write a Python program to find the most frequent words in a text read from
a file.
Algorithm:
1. Read the filename
2. Open the file in read mode
3. Read each line from the file to count the lowers and words
4. Read each line from the file to replace the punctuations
5. Split each line into words and count them
6. Print the words and counts
Program:
def main():
filename=raw_input("enter the file").strip()
infile=open(filename,"r")
wordcounts={}
for line in infile:
processLine(line.lower(),wordcounts)
pairs=list(wordcounts.items())
items=[[x,y] for (y,x) in pairs]
items.sort()
fori in range(len(items)-1,len(items)-11,-1):
print(items[i][1]+"\t"+str(items[i][0]))
defprocessLine(line,wordcounts):
line=replacePunctuations(line)
words=line.split()
for word in words:
if word in wordcounts:
wordcounts[word]+=1
else:
wordcounts[word]=1
defreplacePunctuations(line):
forch in line:
ifch in "~@#$%^&*()_-+=<>?/.,:;!{}[]''":
line=line.replace(ch," ")
return line
main()
Result:
Thus the Python program to find the most frequent words in a text read from
a file is executed successfully and the output is verified.
Aim:
Output:
Ex. No. : 30 SIMULATE ELLIPTICAL ORBITS USING PYGAME Date:
Program:
import math
import random
importpygame
class Particle ():
def init (self, x, y, colour=0x000000):
self.x = x
self.y = y
self.vx = 0
self.vy = 0
self.colour = colour
defapply_gravity (self, target):
dsqd = (self.x - target.x) ** 2 + (self.y - target.y) ** 2
#g = G*m/dsqd * normalized (self - target)
ifdsqd == 0:
return
self.vx += -1 / dsqd * (self.x - target.x) / dsqd ** 0.5
self.vy += -1 / dsqd * (self.y - target.y) / dsqd ** 0.5
def update (self):
self.x += self.vx
self.y += self.vy
pygame.init()
window = pygame.display.set_mode ((600, 400))
main_surface = pygame.Surface ((600, 400))
colours = [0x000000, 0x111111, 0x222222, 0x333333, 0x444444, 0x555555,
0x666666, 0x777777, 0x888888, 0x999999, 0xaaaaaa, 0xbbbbbb] +
[0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,
0x888888, 0xFFFFFF, 0x808000, 0x008080, 0x800080, 0x800000]
#colours = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF,
0x00FFFF, 0x888888, 0xFFFFFF, 0x808000, 0x008080, 0x800080,
0x800000]
Result:
Thus the Python Program to simulate elliptical orbits using Pygame is
executedsuccessfully and the output is verified.
Output:
Ex. No. : 31 SIMULATE BOUNCING BALL USING PYGAME Date:
Aim:
To write a Python program to simulate bouncing ball in Pygame.
Algorithm:
1. Import the required packages
2. Define the required variables
3. Define the screen space to display the bouncing balls in that space
Program:
import sys
importpygame
pygame.init()
screen = pygame.display.set_mode(size)
ball = pygame.image.load('C:\\Users\\admin\\Desktop//ball.jpg')
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
ifevent.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
ifballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
ifballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
Result:
Thus the Python Program to simulate bouncing ball using Pygame is executed
successfully and the output is verified.