0% found this document useful (0 votes)
5 views27 pages

Lab Manual Python With Output

The document outlines various lab sessions involving Python programming exercises. Key tasks include temperature conversions, determining senior citizen status, calculating student marks, identifying triangle types, finding the maximum of five numbers, and implementing factorial and Fibonacci sequence calculations. Additional exercises focus on string manipulation functions, such as counting vowels and digits, reversing numbers, and incrementing dates.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

Lab Manual Python With Output

The document outlines various lab sessions involving Python programming exercises. Key tasks include temperature conversions, determining senior citizen status, calculating student marks, identifying triangle types, finding the maximum of five numbers, and implementing factorial and Fibonacci sequence calculations. Additional exercises focus on string manipulation functions, such as counting vowels and digits, reversing numbers, and incrementing dates.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lab Session- 1

1. Develop Python programs to convert Centigrade temperature into Fahrenheit and to


convert Fahrenheit temperature into Centigrade.

# Centigrade temperature into Fahrenheit


c=float (input ('Enter temperature in Centigrade:'))
f=c*(9/5) +32
print ('temperature in Fahrenheit is: ‘, f)
#Fahrenheit temperature into Centigrade
f1=float (input ('Enter temperature in Fahrenheit:'))
c1=5/9*(f1-32)
print ('temperature in Centigrade is: ‘, c1)

OUTPUT
Enter temperature in Centigrade :35
temperature in Fahrenheit is: 95.0.
Enter temperature in Fahrenheit :95
temperature in Centigrade is: 35.0.
or
# Centigrade temperature into Fahrenheit
x = float (input ('Enter the temperature in degrees: '))
print ('temperature in Fahrenheit is ‘+ str((int(x)*(9/5)) +32) + ' is displayed')
#Fahrenheit temperature into Centigrade
y = int (input ('Enter the temperature in Fahrenheit: '))
print ('temperature in degrees ‘+ str(int(((float(y))-32) *(5/9))) + ' is displayed')

OUTPUT
Enter the temperature in degrees: 35.
temperature in Fahrenheit is 95.0 is displayed.
Enter the temperature in Fahrenheit: 95
temperature in degrees 35 is displayed.
2. Develop a program to read the name and year of the birth of a person. Display whether the
person is a senior citizen or not.

y=input ("Enter the name of the person: \n")


x=int (input ("Enter the year of birth: \n"))
current_year=int (input("Enter current year : \n"))
age=current_year-x
if(age>=60):
print (y," is a Senior citizen")
else:
print (y," is Not a senior citizen")

OUTPUT
(1) (2)
Enter the name of the person: Enter the name of the person:
abc abc
Enter the year of birth: Enter the year of birth:
1960 2000
Enter current year: Enter current year:
2023 2023
abc is a Senior citizen abc is Not a Senior citizen.

3. Develop a program to read USN, Name and marks in three subjects. Print USN, Name of
student, total marks and percentage. Print number of subjects in 1C in which student has
passed.

name=input ('Enter the name of the student:')

usn=input ('Enter the usn of the student:')

print (" ")


print ('Enter marks in 3 subjects')
phy_marks=int (input("Enter marks of the first subject: "))
chem_marks=int (input("Enter marks of the second subject: "))
maths_marks=int (input("Enter marks of the third subject: "))

print ("")
total=phy_marks + chem_marks + maths_marks
percentage=(total/300) *100
print ('Name of the student is',name)
print('USN',usn)
print ('The total is',total,'and the percentage is',percentage)
print (" ")
if(phy_marks>=40 and chem_marks>=40 and maths_marks>=40):
print ('Student has passed in all three subjects')
elif((phy_marks>=40 and chem_marks>=40) or (chem_marks>=40 and maths_marks>=40) or
(phy_marks>=40 and maths_marks>=40)):
print ('Student has passed in two subjects')
elif(phy_marks>=40 or chem_marks>=40 or maths_marks>=40):
print ('Student has passed in only one subjects')
#elif ((phy_marks<40 or chem_marks<40 or maths_marks<40)):
else:
print ('Student has not passed in any subject')

OUTPUT
(1) (2)
Enter the name of the student: abc Enter the name of the student: abc

Enter the usn of the student :123 Enter the usn of the student: 123

Enter marks in 3 subjects Enter marks in 3 subjects.


Enter marks of the first subject: 50 Enter marks of the first subject: 50.
Enter marks of the second subject: 60 Enter marks of the second subject: 60.
Enter marks of the third subject: 100 Enter marks of the third subject: 100

Name of the student is abc Name of the student is abc


USN 123 USN 123
The total is 210 and the percentage is 70.0 The total is 120 and the percentage is 40.0
Student has passed in all three subjects Student has passed in two subjects
(3) (4)
Enter the name of the student:abc Enter the name of the student:abc
Enter the usn of the student :123 Enter the usn of the student :123

Enter marks in 3 subjects Enter marks in 3 subjects


Enter marks of the first subject: 50 Enter marks of the first subject: 30
Enter marks of the second subject: 60 Enter marks of the second subject: 30
Enter marks of the third subject: 100 Enter marks of the third subject: 300

Name of the student is abc Name of the student is abc


USN 123 USN 123
The total is 110 and the percentage is 36.666 The total is 90 and the percentage is 30.0

Student has passed in only one subjects Student has not passed in any subject
Lab session- 2

1. Develop and test a program that determines the type of a triangle. Input sides. Output
types is one of “not a valid triangle”, “equilateral”, “isosceles” or “scalene”.

s1=int (input('enter side1: '))


s2=int (input ('enter side2: '))
s3=int (input ('enter side3: '))
if(s1+s2>s3 and s1+s3>s2 and s2+s3>s1):
print ("it is a valid triangle")
if(s1==s2==s3):
print ('it is equilateral triangle')
elif(s1==s2 or s1==s3 or s2==s3):
print ('it is isosceles triangle')
else:
print ('it is a scalene triangle')
else:
print ('it is not a triangle')

OUTPUT
(1) (2)
enter side1: 2 enter side1:3
enter side2: 2 enter side2:6
enter side3: 2 enter side3:8
it is a valid triangle itis a valid triangle
it is equilatreal triangle it is isosceles triangle

(3) (4)
enter side1: 3 enter side1: 1
enter side2: 6 enter side2: 2
enter side3: 8 enter side3: 3
it is a valid triangle it is not a valid triangle
it is a scalene triangle
2. Develop a program to print the maximum of five numbers. Input five numbers and print
the maximum.

print ("Enter the five numbers")


num1 = int (input ('Enter the number1 : '))
num2 = int (input ('Enter the number2 : '))
num3 = int (input ('Enter the number3 : '))
num4 = int (input ('Enter the number4 : '))
num5 = int (input ('Enter the number5 : '))
if num1>=num2 and num1>=num3 and num1>= num4 and num1>=num5:
print ('number 1 is largest',num1)
elif num2>=num1 and num2>=3 and num2>= num4 and num2>=num5 :
print ('number 2 is largest',num2)
elif num3>=num1 and num3>=num2 and num3>= num4 and num3>=num5 :
print ('number 3 is largest',num3)
elif num4>=num1 and num4>=num2 and num4>= num3 and num4>=num5 :
print ('number 4 is largest : ',num4)
else:
print ('number 5 is largest',num5)

OUTPUT
Enter the five numbers

Enter the number1 : 2

Enter the number2 : 3

Enter the number3 : 1

Enter the number4 : 5

Enter the number5 : 4

number 4 is largest : 5
Lab session- 3
1. Develop a program that inputs names of five students and displays if your name is present
in the five names.
myName=input ('enter your name: \n')
naMe1=input ('enter the name 1 : \n')
naMe2=input ('enter the name 2 : \n')
naMe3=input ('enter the name 3 : \n')
naMe4=input ('enter the name 4 : \n')
naMe5=input ('enter the name 5 : \n')
if (myName == naMe1) or (myName == naMe2) or (myName == naMe3) or (myName ==
naMe4) or (myName == naMe5 ):
print ("hi u r name is : ",myName)
else:
print (" your name is not present in five names")

OUTPUT
(1) (2)
enter your name: abc enter your name : abc
enter the name 1: xyz enter the name 1 : xyz
enter the name 2: lmn enter the name 2 : lmn
enter the name 3: pqr enter the name 3 : pqr
enter the name 4: abc enter the name 4 : abc
enter the name 5: def enter the name 5 : def
hi u r name is: abc your name is not present in five names.

2. Develop a program that computes the factorial of a number N and prints the result. Input
N. Hint: Program uses a loop construct.
#Using while loop
n=int(input("Enter any number:"))
fact=1
i=1
if (n<0):
print("Enter a Positive Integer!")
elif(n==0 or n==1 ):
print("the factorial of a number is: 1")
else:
while(i<=n):
fact=fact*i
i=i+1
print(“the factorial of a number is”,fact)
or
#Using for loop
n=int(input("Enter any number: "))
if(n<0):
print("Enter a Positive Integer!")
elif(n==0 or n==1):
print("the factorial of a number is:",1)
else:
fact=1
for i in range(n,0,-1):
fact=fact*i
print("factorial of a given number is:",fact)

OUTPUT
(1) (2)
enter the number: -1 enter the number : 0
enter positive number the factorial of a number is: 1

(3) (4)
enter the number : 1 enter the number : 5
the factorial of a number is: 1 factorial of a given number is: 120

3. Develop a program that computes the power of a number N and prints the result. Input N.
Hint: program uses a loop construct.
#Calculate power of a number using a while loop
base = int(input("Enter the base value : \n"))
exponent = int(input('Enter the exponrnt value \n'))
result = 1
while exponent != 0 :
#result *= base
result = result * base
exponent =exponent-1
print("Answer = " + str(result))
#Calculate power of a number using a for loop
base = int(input("Enter the base value : \n"))
exponent = int(input('Enter the exponrnt value : \n'))
result = 1
for exponent in range(exponent, 0, -1):
result *= base
print("Answer = " + str(result))

OUTPUT
Enter the base value :
2
Enter the exponrnt value
3
Answer = 8

4. Develop a program that prints the first N numbers of Fibonacci sequence. Input N.
Hint: program uses a loop construct.

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


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

OUTPUT

how many terms? -1 how many terms?

please enter a positive integer Fibonacci sequence:

2
Lab session- 4
1. Write a function that returns the number of vowels in a string.

def count_vowels(x): | def count_vowels(x):


vowels = ['a', 'e', 'i', 'o', 'u'] | count = 0
count = 0 | for i in x.lower :
x = x.casefold() | if i in “a” ”e” ”i” ”o” ”u”:
for i in x: | count += 1
if i in vowels: | return count
count += 1 |
print("The total count of vowels is:", count) | str1 = input('Enter the input string:\n')
| print(count_vowels(str1))
str1 = input('Enter the input string:\n') |
count_vowels(str1) |

OUTPUT
Enter the input string:

PythonLab

The total count of vowels is: 2

2. Write a function that returns the number of digits in a string.

def is_digit(x):

digit=0
char=0
for i in x:
if i.isdigit():
digit+=1
else :
char= char+1
print('count of char is : ',char)
print('count of digit is : ',digit)
x=input("Enter the sting \n")
is_digit(x)

OUTPUT
(1) (2)
Enter the sting Enter the sting
1245abcd 111
count of char is : 4 count of char is : 0
count of digit is : 4 count of digit is : 3

(3)
Enter the sting
abcd
count of char is : 4
count of digit is : 0

3. Write a function that outputs the number obtained by reversing the digits of a number

def reverse_number(n):
r=0
while n>0:
d=n%10
r=r*10+d
n=n//10
return r
n = int(input(“enter number: ”))
r=reverse_number(n)
print("Reversed number is :", r)

OUTPUT

enter number123

Reversed number is : 321


4. Write a function that returns the date obtained by incrementing date input in the format
ddmmyyyy.

def date1(date):
dd,mm,yyyy=date.split("/")
dd=int(dd)
mm=int(mm)
yyyy=int(yyyy)
if mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12:
max1=31
elif mm==4 or mm==6 or mm==9 or mm==11:
max1=30
elif yyyy%4==0 and yyyy%100!=0 or yyyy%400==0:
max1=29
else:
max1=28

if mm<1 or mm>12:
return'month is invalid'
elif dd<1 or dd>max1:
return'date is invalid'
elif dd==max1 and mm<12:
dd=1
mm=mm+1
print('incremented date is :')
return (dd,mm,yyyy)
elif dd==31 and mm==12:
dd==1
mm==1
yyyy=yyyy+1
print('incremented date is :')
return(dd,mm,yyyy)
else:
dd=dd+1
print('incremented date is :')
return (dd,mm,yyyy)
date=input('enter the date:')
result=date1(date)
print(result)

OUTPUT

(1) (2) (3)

enter the date:01/01/2023 enter the date:31/01/2023 enter the date:29/02/2024

incremented date is : incremented date is : incremented date is :

(2, 1, 2023) (1, 2, 2023) (1, 3, 2024)

(4) (5)
enter the date:31/12/2023 enter the date:29/02/2023

incremented date is : date is invalid


(31, 12, 2024)
Lab session- 5

1. Develop a function that returns true if input string is a palindrome; otherwise it returns
false.

def check_palindrome(string): | def isPalindrome(st):


revstr = "" | return s==s[::-1]
for i in string: | s=input("Enter a string: ")
revstr = i + revstr | ans= isPalindrome(st):
print("Reversed string: ", revstr) | if ans:
if string == revstr: | print(“True”)
return True | else:
else: | print(“False”)
return False |
|
input_string = input("Enter a string: ") |
print(check_palindrome(input_string)) |

OUTPUT
(1) (2)
Enter a string: MOM Enter a string: PythonLab
Reversed string: MOM Reversed string: baLnohtyP
True False

2. Input N numbers and create a list. Develop a program to print mean, variance and
standard deviation of the numbers with appropriate messages.

import math
list1=[]
print ('enter size of list')
num= int (input ())
print ('enter the elements into the list')
for i in range(num):

x=int(input())
list1.append(x)
print('The elements in the list are',list1)
n =len(list1)
numerator_total=0
sum=0
for k in list1:
sum= sum+k
mean=sum/n
for x in list1:
var= (x - mean)**2
numerator_total=numerator_total+var

variance= numerator_total/(n-1)

std_dev=math.sqrt(variance)

print('Mean=', mean)
print('Variance=',variance)

OUTPUT
enter size of list

4
enter the elements into the list
2
3
4
5
The elements in the list are [2, 3, 4, 5]
Mean= 3.5
Variance= 1.6666666666666667
or
def calc_average(lst):
return sum(lst) / len(lst)

def calc_variance(lst, mean_value):


ans= sum((i - mean_value) ** 2 for i in lst) / (len(lst) – 1)
return ans

def calc_stdev(variance):
res=variance ** 0.5
return res

lst = [1, 2, 3, 4, 5, 6]
mean_value = calc_average(lst)
print("Mean of the list is", mean_value)

variance = calc_variance(lst, mean_value)


print("Variance of the list is", variance)

standard_deviation = calc_stdev(variance)
print("Standard deviation of the list is", standard_deviation)

OUTPUT
Mean of the list is 3.5

Variance of the list is 3.5

Standard deviation of the list is 1.8708286933869707


3. Input a multi-digit number (as chars) and develop a program that prints the frequency of
each digit with suitable messages.

n = input("Enter the number : ") | def char_frequency(str1):


digit = input("num to find the occurance : ") | dict = {}
def freq(): | for n in str1:
count = 0 | keys = dict.keys()
for i in n: | if n in keys:
if i == digit: | dict[n] += 1
count += 1 | else:
print(count) | dict[n] = 1
freq() |
| return dict
OUTPUT |
Enter the number : 111233 | a=input('Enter the number:')
num to find the occurance : 1 | print(char_frequency(a))

3 OUTPUT

Enter the number:111233

{'1': 3, '2': 1, '3':

4. Develop a function that accepts a point in a plane as an argument or arguments and returns
a string. indicating in which quadrant the point lies, or if it lies on an axis or is the origin
itself.

def quadrant(x, y):

if (x > 0 and y > 0):

return ("lies in First quadrant")

elif (x < 0 and y > 0):

return ("lies in Second quadrant")


elif (x < 0 and y < 0):

return ("lies in Third quadrant")

elif (x > 0 and y < 0):

return ("lies in Fourth quadrant")

elif (x == 0 and y > 0):

return ("lies at positive y axis")

elif (x == 0 and y < 0):

return ("lies at negative y axis")

elif (y == 0 and x < 0):

return ("lies at negative x axis")

elif (y == 0 and x > 0):

return ("lies at positive x axis")

else:

return ("lies at origin")

x=int(input('enter x point'))

y=int(input('enter y point'))

print(quadrant(x,y))
OUTPUT

(1) (2) (3) (4)

enter x point 1 enter x point -1 enter x point -1 enter x point 1

enter y point 2 enter y point 2 enter y point -2 enter y point -2

lies in First quadrant lies in Second quadrant lies in Third quadrant lies in Third quadrant

(5) (6) (7)

enter x point 0 enter x point 0 enter x point 1

enter y point 2 enter y point -2 enter y point 0

lies at positive y axis lies at negative y axis lies at positive x axis

(8)

enter x point -1

enter y point 0

lies at negative x axis


Lab Session : 6

1. Develop a program to print 10 most frequently appearing words in a text file. Use
dictionary data type.

import os

wordCounts = {}

fileHandler = open('sample.txt')

def removePunctuations(string):
PUNCTUATIONS = "!()-[]{}\,./?@#$%^*_~"
for ele in string:
if ele in PUNCTUATIONS:
string = string.replace(ele,' ')
return string
for line in fileHandler:
line = removePunctuations(line).lower()
for word in line.split():
if word in wordCounts:
wordCounts[word] += 1
else:
wordCounts[word] = 1
lst = []
for key, val in list(wordCounts.items()):
lst.append((val, key))

lst.sort(reverse=True)

finalList = []
for val, key in lst:
finalList.append((key, val))
print(dict(finalList[0:10]))
2. Develop a program to add two matrices represented using Python lists.

L1=[[1,2,5],[4,3,1],[2,6,8]]
L2=[[3,6,-1],[2,9,5],[1,6,0]]

Result=[[0,0,0],[0,0,0],[0,0,0]]

for i in range(len(L1)):
for j in range(len(L1[0])):
Result[i][j]=L1[i][j]+L2[i][j]

print('Addition of two matrices')


for i in range(3):
for j in range(3):
print(Result[i][j], end=' ')
print()

OUTPUT

Addition of two matrices

484

6 12 6

3 12 8

3. Develop a program to multiply two matrices using Python lists.

L1=[[1,2,3],[2,3,4],[3,4,5]]
L2=[[1,2,1],[2,2,3],[3,2,1]]
Result=[[0,0,0],[0,0,0],[0,0,0]]
# iterate through rows of L1
for i in range(len(L1)):
# iterate through columns of L2
for j in range(len(L2[0])):
# iterate through rows of L2
for k in range(len(L2)):
Result[i][j]=Result[i][j]+L1[i][k]*L2[k][j]
print('Multiplication of two matrices')

for i in range(len(L1)):
for j in range(len(L2)):
print(Result[i][j], end=' ')
print()

OUTPUT

Multiplication of two matrices

14 12 10 20 18 15 26 24 20
Lab Session 7:
1. Develop a program to add two sparse matrices. Hint: Use a Dictionary.

matrix1 = [[0, 0, 0, 1, 0],


[2, 0, 0, 0, 3],
[0, 0, 0, 4, 0]]
matrix2 = [[0, 1, 0, 4, 0],
[0, 0, 0, 3, 0],
[1, 4, 0, 0, 2]]
def convertToDictionary(matrix):
dct = {}
for i in range(len(matrix)): # Iterate through rows
for j in range(len(matrix[0])): # Iterate through columns
if matrix[i][j] != 0:
dct[i, j] = matrix[i][j]
return dct
dictionaryMatrix1 = convertToDictionary(matrix1)
dictionaryMatrix2 = convertToDictionary(matrix2)
def addSparseMatrix(first, second):
resultantDict = {}
allKeys = list(first.keys()) + list(second.keys())
for keyIterator in allKeys:
firstValue = first.get(keyIterator, 0)
secondValue = second.get(keyIterator, 0)
sumOfValues = firstValue + secondValue
if sumOfValues != 0:
resultantDict[keyIterator] = sumOfValues
return resultantDict
res = addSparseMatrix(dictionaryMatrix1, dictionaryMatrix2)
print(res)

OUTPUT
{}
2. Develop a recursive function to perform binary search on a sorted list of names. The
function returns the position of a name passed as argument to the function.

def binary_search(list, low, high, elem_to_search):


if high >= low:
mid = (low + high) // 2
if elem_to_search == list1[mid]:
return mid
elif elem_to_search < list1[mid]:
return binary_search(list, low, mid-1, elem_to_search)
else:
return binary_search(list, mid+1, high, elem_to_search)
else:
return -1

list1 = ["Ram","Sita","Veena"]
low=0
high=len(list1)-1
elem_to_search = "Sita"

result = binary_search(list1,low,high,elem_to_search)

if result == -1:
print("Element not found!")
else:
print("Element found at index ", result)

OUTPUT
Element found at index 1
Lab Session 8:
1. Develop a program to read the contents of a text file, sort contents read and write the sorted
contents into a separate text file.

import os
fhand=open('1.txt','r')
#fhand=open('C:\\Users\\hp india\\Desktop\\newsample.txt','r')
content = fhand.read()
content = content.split('\n')
content.sort()
fhand=open('write.txt','w')
#fhand=open('C:\\Users\\hp india\\Desktop\\newsamplewrite.txt','w')
for word in content:
fhand.write(word +'\n')
fhand.close()
2. Develop an iterative solution for binary search
list1= [ 2, 3, 4, 10, 40 ]
elem_to_search = 40
low=0
high=len(list1)-1
while low <= high:
mid = (high + low) // 2
if(list1[mid]==elem_to_search):
print('element present at',mid)
break
elif list1[mid] < elem_to_search:
low = mid + 1
else:
high=mid-1
else:
print('element not found')

OUTPUT

element present at 4

You might also like