YUVARAJA’S COLLEGE MYSORE
Department of Computer Science
V Semester BSC– 2023 –PROGRAMMING IN PYTHON- LAB PROGRAMS
Part A
1. Check if a given number belongs to the Fibonacci Sequences
2. Solve quadratic Equations
3. Find the sum of natural numbers
4. Display Multiplication tables
5. Check if a given number is a Prime number or not
6. Implement a sequential search
7. Create a calculator program
8. Explore string functions
9. Implement selection sort
10.Implement Stack
11.Read and write a file
PART -B
1. Program to demonstrate usage of basic regular expression
2. Program to demonstrate uses of list in Python
3. Program to demonstrate use of dictionaries
4. Create a GUI using Tkinter module
5. Demonstrate Exceptions in Python
Part A
1. Program to check the given number belongs to the Fibonacci Sequences
# check the given number belongs to the Fibonacci Sequences
n=int(input("enter the number you want to check"))
fn=0
sn=1
sum=1
if n==0 and n==1:
print("Given number is fibonacci number")
else:
while fn<n:
sum=fn+sn
fn=sn
sn=sum
if fn==n:
print("Given number is fibonacci number")
else:
print("Given number is not fibonacci number")
OUTPUT:
enter the number you want to check 8
Given number is fibonacci number
enter the number you want to check 7
Given number is not fibonacci number
#2. To implement Quadratic equation
import math
a=int(input("enter a:"))
b=int(input("enter b:"))
c=int(input("enter c:"))
d=(b**2)-(4*a*c)
deno=2*a
if d==0:
print("Repeated roots")
r1=-b/deno
r2=r1
print("r1=",r1)
print("r2=",r2)
elif d>0:
print("Real and distinct roots")
r1=(-b-math.sqrt(d))/deno
r2=(-b+math.sqrt(d))/deno
print("root1=",r1)
print("root2=",r2)
else:
print("complex and imaginary")
realpart=-b/deno
complexpart=math.sqrt(abs(d))/deno
print("root1=" ,realpart, "+j")
print("root2=" ,complexpart, "-j")
output:
enter a:1
enter b:2
enter c:-3
Real and distinct roots
root1= -3.0
root2= 1.0
enter a:1
enter b:2
enter c:1
Repeated roots
r1= -1.0
r2= -1.0
enter a:2
enter b:-10
enter c:25
complex and imaginary
root1= 2.5 +j
root2= 2.5 -j
#3.Program to find the sum of natural numbers
num=int(input("enter a number"))
sum = 0
for i in range(1,num+1):
sum+=i
print("sum of natural number:",num,"=", sum)
output:
enter a number10
sum of natural number: 10 = 55
enter a number1
sum of natural number: 1 = 1
enter a number1
sum of natural number: 0 = 0
#4.to display the multiplication table
n=int(input("ener the start table number="))
m=int(input("enter the end table number="))
for i in range(n,m+1):
for j in range(1,11):
print( i,"X",j,'=',i*j,end='\n')
print("\n")
ener the start table number=2
enter the end table number=3
2X1=2
2 X 2=4
2 X 3=6
2 X 4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3 X 1=3
3 X 2=6
3 X 3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
#5. to check if a given number is prime number or not
number=int(input("enter any number"))
if number>=1:
for i in range(2,number):
if number%i==0:
print(i) # divisor
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")
else:
print(number,"is a not a prime number")
output:
enter any number2
2 is a prime number
enter any number1
1 is a prime number
enter any number45
45 is not a prime number
enter any number17
17 is a prime number
#6.Program to implement a sequential search
arr=[]
# to input elements
n=int(input("enter n :"))
print("enter the elements")
for i in range(0,n):
element=int(input())
arr.append(element)
#to output elements
print(" elements are:\n")
print(arr)
#sequential search
se=int(input("enter search element:\t"))
loc=-1
for i in range(0,n):
if arr[i]==se:
loc=i
print(se," found in position",loc+1)
if loc==-1:
print(se,"does not occur")
#7.Program to create a calculator program
def add(x,y):
return x+y
def sub(x,y):
return x-y
def pro(x,y):
return x*y
def quo(x,y):
return x/y
def rem(x,y):
return x%y
def intquo(x,y):
return x//y
def power(x,y):
return x**y
print ("simple calculator")
print("----------------")
while True:
print("select operation")
print(" 1.addition\t","2.difference\t","3.product\t","4.quotient\t",
"5.remainder\t","6.intquotient\t","7.exponent\t","8.exit")
choice=int(input("enter your choice"))
if choice==8:
print("BYE")
break
n1=int(input("enter n1="))
n2=int(input("enter n2="))
if choice==1:
print(n1,"+",n2,"=",add(n1,n2))
elif choice==2:
print(n1,"-",n2,"=",sub(n1,n2))
elif choice==3:
print(n1,"*",n2,"=",pro(n1,n2))
elif choice==4:
print(n1,"/",n2,"=",quo(n1,n2))
elif choice==5:
print(n1,"%",n2,"=",rem(n1,n2))
elif choice==6:
print(n1,"//",n2,"=",intquo(n1,n2))
elif choice==7:
print(n1,"**",n2,"=",power(n1,n2))
else:
print("invalid operator")
#8.Program to explore string functions
while True:
print("select operation")
print("1.swapcase()\t2.join()\t3.replace()\n4.split()\t5.length()\t6.exit()")
choice=int(input("Enter your choice:"))
if choice>=6:
print("bye")
print("invalid choice")
break
elif choice==1:
str1=input("Enter a string to convert:")
print("to convert a string to upper or lowercase=",str1.swapcase())
elif choice==2:
str1=input("Enter a string1:")
str2=input("Enter a string2:")
print("to join two strings="," ".join([str1,str2]))
elif choice==3:
str1=input("Enter a source string:")
str2=input("Enter a destination string:")
print("to replace a string by other string",str1.replace(str1,str2))
elif choice==4:
str1=input("Enter a text:")
print(" to split the strings",str1.split())
elif choice==5:
str1=input("enter a string to find length :")
n=len(str1)
print(" the length of the string" ,n)
else :
exit()
#9.Program to implement selection sort
arr=[]
n=int(input("enter n :"))
print("enter the elements")
for i in range(0,n):
element=int(input())
arr.append(element)
print(" elements are:\n")
for i in range(0,n):
print(arr[i])
# selection sort
for i in range(0,n):
small=i
for j in range(i+1,n):
if arr[j]< arr[small]:
temp =arr[j]
arr[j]=arr[small]
arr[small]=temp
print(" After sorting the elements are:\n")
for i in range(0,n):
print(arr[i])
#10 Program to implement stack using list(data structure)
stack=[]
# Push operation
def push():
if len(stack)==n:
print("stack is full")
else:
element=int(input("enter the elements to the stack="))
stack.append(element)
print(stack)
# Pop operation
def pop():
if len(stack)==0:
print("stack is empty")
else:
e=stack.pop()
print("removed element=",e)
print(stack)
# Display operation
def display():
if len(stack) == -1:
print("stack is empty")
else:
top=len(stack)-1
print("stack elements are:\n")
for i in range(top,-1,-1):
print(stack[i])
# main function(calling function)
while True:
print(" 1.push()\n2.pop()\n3.display()\n4.exit()")
choice=int(input("enter your choice="))
if choice>=4:
print("invalid")
break
n=int(input("limit of stack:"))
if choice==1:
push()
elif choice==2:
pop()
elif choice==3:
display()
else:
print("invalid choice")
break
PART A :11 PROGRAM : TO READ AND WRITE INTO A FILE
f=open("E:\\textfiles\newfile1.txt","w")
str1=f.write(“welcome to our college”)
print("the text is:")
print(str1)
#to read a file
f1=open("E:\\textfiles\\newfile2.txt","r")
str2=f1.write()
print(lstr2)
PART B
#PART B- 1. Program to demonstrate usage of basic regular expression
import re
print(' 1.findall \n 2. search \n 3. split \n 4. sub \n')
txt = "A freind in need is a freind indeed"
print('\n',txt)
#Return a list containing every occurrence of "in":
x = re.findall("in", txt)
print('\n the list of occurrence of in \n',x)
x = re.findall("[a-m]", txt)
print(x)
#Returns a Match object if there is a match anywhere in the string
x = re.search("i", txt)
print("\n The character i is located in position:\n", x.start())
#Split the string at every white-space character:
x = re.split("\s", txt)
print('\n after spliting the text is:\n',x)
#Replace all white-space characters with the digit "9":
x = re.sub("\s", "9", txt)
print('\n after replacing all spaces with digit 9:\n',x)
#PART B-3.Program to demonstrate uses of list in Python
list1=[]
while True:
print("1.append()\n2.insert()\n3.sort()\n4.reverse()\n5.pop()\n6.exit()")
choice=int(input("enter your choice:"))
if choice==1:
n=int(input("enter n:"))
print("enter the elements to list:")
for i in range(0,n):
element=int(input())
list1.append(element)
elif choice==2:
ele=int(input("enter a element to insert"))
loc=int(input("enter the location to insert"))
list1.insert(loc,ele)
print("the list after insertion :\n",list1)
elif choice==3:
list1.sort()
print("the sorted elements are:\n",list1)
elif choice==4:
list1.reverse()
print("the list after reversing:\n",list1)
elif choice==5:
loc=int(input("enter the location to delete"))
list1.pop(loc)
print("the list after deletion:\n",list1)
else:
print("invalied number")
quit()
#PARTB-4.Program to demonstrate use of dictionaries
import meaningfile
m=meaningfile.meanings
print("\n the meaning dictionary is\n")
print(m.items())
word=input("\nsearch a word for meaning:")
if word in m:
print('the meaning of',word,'is:',end=' ')
print(m[word])
else:
print('the meaning of',word,'does not exist')
# To create a file and store meanings
Start programs notepad save as meaningfile.py
meanings={“compute”:”operate”,”bug”:”error”,”find”:”search”,
”buffer”:memory”}
File->save
#PARTB-5.Program to create SQLite database and perform operations on
table
import sqlite3
conn = sqlite3.connect('test.db')
#TO CREATE A TABLE
print ("Opened database successfully")
conn.execute('''CREATE TABLE STUDENT10(ID NOT NULL,NAME TEXT NOT NULL,TOTAL
INT,AVG REAL);''')
print ("Table created successfully")
#INSERT OPERATION
print("To insert records into the table\n")
conn.execute("INSERT INTO STUDENT10 (ID,NAME,TOTAL,AVG)VALUES
(101,'TOM',578,84.56)");
conn.execute("INSERT INTO STUDENT10 (ID,NAME,TOTAL,AVG)VALUES
(102,'ARUN',500,80.6)");
conn.execute("INSERT INTO STUDENT10 (ID,NAME,TOTAL,AVG)VALUES
(103,'VEENA',467,75.9)");
print("\n to display the records: \n")
cursor = conn.execute("SELECT ID,NAME,TOTAL,AVG FROM STUDENT10")
for row in cursor:
print("ID = ", row[0])
print("NAME = ", row[1])
print("TOTAL = ", row[2])
print("AVG = ", row[3])
#UPDATION OPERATION
conn.execute("UPDATE STUDENT10 set TOTAL =550 where ID = 102")
print("UPDATED ROW IS :\n")
cursor = conn.execute("SELECT ID,TOTAL from STUDENT10")
print("ID=",row[0])
print("TOTAL=",row[2])
#DELETE OPERATION
conn.execute("DELETE from STUDENT10 where ID = 103;")
print("\n the deleted row is",row[0])
cursor = conn.execute("SELECT ID,NAME,TOTAL,AVG from STUDENT10")
for row in cursor:
print("ID = ", row[0])
print("NAME = ", row[1])
print("TOTAL = ", row[2])
print ("AVG = ", row[3])
conn.close()
Tkinter module
"""Tkinter is the standard GUI library for Python.Python when combined with Tkinter
provides a fast and easy wayto create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit."""
#PART B-6. Create a GUI using Tkinter module
import tkinter as Tk
top = tkinter.Tk()
# Code to add widgets will go here...
#greeting = Tk.Label(text="Hello, Tkinter")
top.mainloop()
# PART B-7 –Demonstrate Exceptions in Python
# exceptions
def divide():
try:
a=4
b=0
print(a/b)
except Exception as e:
print("the error is=",e)
print("the value cannot be divide by 0")
finally:
print("program is closed")
#exception 2
def index():
try:
a=[10,20,30]
print(a[4])
except Exception as e:
print("The error is=",e)
print("invalied index")
finally:
print("program is closed")
def module():
try:
import picklle
except Exception as e:
print("The error is=",e)
finally:
print("program is closed")
while True:
choice=int(input("enter your choice:"))
if choice==4:
print("invalied choice")
break
elif choice==1:
divide()
elif choice==2:
index()
elif choice==3:
module()