Exam Lab Manual
Exam Lab Manual
(c) create, concatenate and print a string and accessing substring from a given string
a=input("Enter 1st string:")
b=input("Enter 2nd string:")
print("String 1:",a)
print("String 2:",b)
print("Concatenated string is:",a+" "+b)
print("Substrings:")
print(a[1:4])
print(a[:-2])
print(b[2:6])
print(b[:])
EXP 2:
(a) print the current date in the following format “WED 09 02:26:23 IST 2020”.
import time
loc=time.localtime()
print(time.strftime("%b %d %X %Z %Y",loc))
(b) convert temperatures to and from Celsius, Fahrenheit
print("1.Celsius to Fahrenheit")
print("2.Fahrenheit to Celsius")
ch=int(input("Enter choice:"))
if ch==1:
c=int(input("Enter temp in celsius:"))
f=(((9/5)*c)+32)
print("Fahrenheit is: ",f)
elif ch==2:
f=int(input("Enter temp in fahrenheit:"))
c=((f-32)*5)/9
print("Celsius is: ",c)
else:
print("Enter 1 or 2!!")
EXP 3:
(a) factorial of a number using Recursion
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
num=int(input("Enter a number:"))
if num<0:
print("Invalid input!")
elif num==0:
print("Factorial of 0 is 1")
else:
print("Factorial is",factorial(num)
#save as fib.py
import fibonaccimodule
n=int(input("Enter the number of terms: "))
fibonaccimodule.fib(n)
EXP 4:
(a) Prompt the user for the names of two text files, the contents of the first file should be input and
written to the second file
file1=input("Enter the first file name:")
fptr1=open(file1,"r")
if fptr1==0:
print("Error in opening the file")
exit(1)
lines=fptr1.readlines()
file2=input("Enter the second file name:")
fptr2=open(file2,"w")
if fptr2==0:
print("Error in opening the file")
exit(1)
fptr2.writelines(lines)
print("Success")
fptr1.close()
fptr2.close()
(b) Input a text file and print all of the unique words in the file in alphabetical order.
fname=input('Enter file name:')
fh=open(fname)
lst=list()
words=list()
for line in fh:
words+=line.split()
words.sort()
print('The unique words in alphabetical order are:')
for word in words:
if word in lst:
continue
else:
lst.append(word)
print(word)
(c) class to convert an integer to a roman numeral
class Number_to_Roman:
def printRoman(self,number):
num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
sym = ["I", "IV", "V", "IX", "X", "XL","L", "XC", "C", "CD", "D", "CM", "M"]
i = 12
while number:
div = number // num[i]
number %= num[i]
while div:
print(sym[i], end = "")
div -= 1
i -= 1
number = int(input('Enter a value:'))
print("Roman value is:",end="")
Number_to_Roman().printRoman(number)
EXP 5:
(a) Class to implement pow(x, n)
class pownum:
def power(self,x,n):
pow=1
for i in range(n):
pow=pow*x
return pow
x=int(input("Enter value for base:"))
n=int(input("Enter value for exponent:"))
print(pownum().power(x,n))
EXP 6:
(a) Count the numbers of characters in the string and store them in a dictionary data structure
num=int(input("Enter the number of words:"))
list=[]
for i in range(1,num+1):
s=input("Enter word:")
list.append(s)
print("The list is:",list)
dict={}
for i in list:
dict[i]=len(i)
print("The dictionary is:",dict)
(b) Use split and join methods in the string and trace a birthday with a dictionary data structure.
birthday={"Vinay":"18-01-2024","Vishnu":"23-05-2023","Leela":"10-03-2022","Yash":"29-11-2021"}
s=input("Enter a name:")
list=s.split()
for i in list:
if i in birthday.keys():
name=i
print("Birthday is:",birthday[name])
EXP 7:
(a) Combines lists into a dictionary
sub=["M3","OS","DBMS","CN","C"]
marks=[82,93,98,83,90]
a=zip(sub,marks)
print(dict(a))
(b) Count frequency of characters in a given file. Use character frequency to tell which type of file it is.
import os
count =0
filename=input("Enter the file name:")
file=open(filename)
for line in file:
for l in range(0,len(line)):
count+=1
print("count:",count)
filename,file_extension=os.path.splitext(filename)
print("file_extension==",file_extension)
if(file_extension=='.py'):
print("Its a python program file")
elif(file_extension==".txt"):
print("Its a text file")
elif(file_extension==".c"):
print("Its a C program file")
EXP 8:
(a) Function ball collides that takes two balls as parameters and computes if they are colliding. Your
function should return a Boolean representing whether or not the balls are colliding
import math
def ballcollides(x1,y1,r1,x2,y2,r2):
status=False
d=math.sqrt((x2-x1)**2-(y2-y1)**2)
r=r1+r2
if(d<r):
status=True
else:
status=False
return status
s=ballcollides(1,2,4,111,102,3)
print("Balls Collision is",s)
s=ballcollides(1,2,2,101,102,3)
print("Balls Collision is",s)
(b) Mean, median, mode for the given set of numbers in a list
li = list(map(int, input('Enter list of elements: ').split()))
l = len(li)
mean = sum(li)/l
li.sort()
median = li[l//2]
mode = max(set(li),key=li.count)
print("Mean :",mean)
print("Median :",median)
print("Mode :",mode)
EXP 9:
(a) Function nearly equal to test whether two strings are nearly equal
def nearly_equal(str1,str2):
count=0
i=j=0
while(i<len(str1) and j<len(str2)):
if(str1[i]!=str2[j]):
count=count+1
if(len(str1)>len(str2)):
i=i+1
elif(len(str1)==len(str2)):
pass
else:
i=i-1
if(count>1):
return False
i=i+1
j=j+1
if(count<2):
return True
str1=input("Enter String1:\n")
str2=input("Enter String2:\n")
boolean=nearly_equal(str1,str2)
if(boolean):
print("Strings are nearly equal.")
else:
print("Strings are not equal.")
EXP 10:
(a) Define a matrix and print it
import numpy as np
print("Creating a matrix using list")
lst=[[1,2,3],[4,5,6],[7,8,9]]
print(lst)
print("Creating a matrix using numpy")
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print(type(a))
print(a.ndim)
EXP 11:
(a) Install packages requests, flask and explore them using (pip)
pip install flask
pip install requests
(b) imports requests and fetch content from the page E.g.wikipedia
import requests as req
res = req.get('https://www.wikipedia.com')
print(res.content[:47])
EXP 12:
(a) GUI for an Expression Calculator using tk
from tkinter import *
def button_click(char):
global expression
expression += str(char)
input_field.set(expression)
def button_equal():
try:
global expression
result = str(eval(expression))
expression = result
input_field.set(result)
except:
input_field.set("Error")
def button_clear():
global expression
expression = ""
input_field.set("")
expression = ""
window = Tk()
window.title("Expression Calculator")
window.geometry("330x270")
window.configure(bg="light blue")
input_field = StringVar()
entry = Entry(window, textvariable=input_field, width=50, borderwidth=5)
entry.grid(columnspan=4, padx=10, pady=10)
button_7 = Button(window, text='7', width=5, height=2, command=lambda: button_click(7))
button_7.grid(row=1, column=0)
button_8 = Button(window, text='8', width=5, height=2, command=lambda: button_click(8))
button_8.grid(row=1, column=1)
button_9 = Button(window, text='9', width=5, height=2, command=lambda: button_click(9))
button_9.grid(row=1, column=2)
button_4 = Button(window, text='4', width=5, height=2, command=lambda: button_click(4))
button_4.grid(row=2, column=0)
button_5 = Button(window, text='5', width=5, height=2, command=lambda: button_click(5))
button_5.grid(row=2, column=1)
button_6 = Button(window, text='6', width=5, height=2, command=lambda: button_click(6))
button_6.grid(row=2, column=2)
button_1 = Button(window, text='1', width=5, height=2, command=lambda: button_click(1))
button_1.grid(row=3, column=0)
button_2 = Button(window, text='2', width=5, height=2, command=lambda: button_click(2))
button_2.grid(row=3, column=1)
button_3 = Button(window, text='3', width=5, height=2, command=lambda: button_click(3))
button_3.grid(row=3, column=2)
button_0 = Button(window, text='0', width=5, height=2, command=lambda: button_click(0))
button_0.grid(row=5, column=0)
button_divide = Button(window, text='/', width=5, height=2, command=lambda: button_click("/"))
button_divide.grid(row=1, column=3)
button_multiply = Button(window, text='*', width=5, height=2, command=lambda: button_click("*"))
button_multiply.grid(row=2, column=3)
button_subtract = Button(window, text='-', width=5, height=2, command=lambda: button_click("-"))
button_subtract.grid(row=3, column=3)
button_add = Button(window, text='+', width=5, height=2, command=lambda: button_click("+"))
button_add.grid(row=4, column=3)
button_clear = Button(window, text='Clear', width=5, height=2, command=button_clear)
button_clear.grid(row=4, column=0)
button_dot = Button(window, text='.', width=5, height=2, command=lambda: button_click("."))
button_dot.grid(row=4, column=1)
button_equal = Button(window, text='=', width=5, height=2, command=button_equal)
button_equal.grid(row=4, column=2)
window.mainloop()
#First Image
import turtle as t
t.speed('fastest')
def Exp12bI():
t.pensize(2)
c = ['red', 'light green', 'blue']
for i in range(12):
t.color(c[i % 3])
t.circle(75)
t.right(30)
t.mainloop()
Exp12bI()
#Second Image
import turtle as t
t.speed('fastest')
def Exp12bII():
for i in range(45):
for i in range(4):
t.forward(100)
t.right(90)
t.right(8)
t.mainloop()
Exp12bII()
EXP 13:
(a) Test-case to check the function even numbers which return True on passing a list of all even
numbers.
import unittest
def even_numbers(lst):
count=0
for i in lst:
if i%2==0:
count=count+1
if count==len(lst):
return True
else:
return False
class TestEven(unittest.TestCase):
def test_even_numbers(self):
self.assertTrue(even_numbers(numlist))
num_input= input("Enter numbers separated by spaces: ")
numlist = list(map(int, num_input.split()))
unittest.main()
(b) Test-case to check the function reverse string which returns the reversed string.
import unittest
def reverse(str):
s=' '
s=str[len(str)-1::-1]
return s
class TestReverse(unittest.TestCase):
def test_reverse(self):
self.assertEqual(reverse(stringinput),stringinput)
stringinput=input("Enter a string:")
unittest.main()
EXP 14:
(a) Ask the user for an algebraic expression and then inserts multiplication symbols where
appropriate.
import re
exp=input('Enter an expression:')
pattern=r'\d[a-zA-Z]'
exp=re.sub(r'((?:\d+)|(?:[a-zA-Z]\w*\(\w+\)))((?:[a-zA-Z]\w*)|\()',r"\1*\2",exp)
print(f'Modified expression:{exp}')
(b) Asks the user to enter a length in feet. The program should then give the user the option to convert
from feet into inches, yards, miles, millimeters, centimeters, meters, or kilometers.
feet = int(input("Enter a length in feet: "))
print("""Choose an option to convert:
1.Feet to Inches
2.Feet to Yards
3.Feet to Miles
4.Feet to Millimeters
5.Feet to Centimenters
6.Feet to Meters
7.Feet to Kilometers""")
integer = int(input("Option:"))
inches = feet * 12
yards = feet * 0.33333
miles = feet * 0.000189393939
millimeters = feet * 304.8
centimeters = feet * 30.48
meters = feet * 0.3048
kilometers = feet * 0.0003048
convert = [feet,inches,yards,miles,millimeters,centimeters,meters,kilometers]
print(convert[integer])
EXP 15:
(a) Read a file consisting of email addresses each on its own line. Then print out a string consisting of
those email addresses separated by semicolons.
filename = input('Enter a File Name :')
with open(filename, 'r') as f:
lines = [line.strip() for line in f.readlines()]
s = ';'.join(lines)
print(s)
(b) Read a list of temperatures from a file called temps.txt and converts those temperatures to
Fahrenheit and write the results to a file called ftemps.txt.
filename1 = input("Enter File 1:")
filename2 = input("Enter File 2:")
converter = lambda c_temp: (9 / 5) * c_temp + 32
f1 = open(filename1, 'r')
f2 = open(filename2, 'w')
for line in f1.readlines():
f2.write(str(converter(int(line))) + '\n')
f1.close()
f2.close()
print('Converted Successfully')