0% found this document useful (0 votes)
3 views14 pages

Python Lab Updated Manual

The document is a Python lab manual containing various programming exercises. It includes programs for checking Fibonacci numbers, solving quadratic equations, calculating sums, displaying multiplication tables, checking for prime numbers, implementing search algorithms, creating a calculator, and demonstrating string functions, among others. Additionally, it covers data structures like stacks, file operations, regular expressions, lists, dictionaries, exception handling, and data visualization with Matplotlib.

Uploaded by

nandeesh262371
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)
3 views14 pages

Python Lab Updated Manual

The document is a Python lab manual containing various programming exercises. It includes programs for checking Fibonacci numbers, solving quadratic equations, calculating sums, displaying multiplication tables, checking for prime numbers, implementing search algorithms, creating a calculator, and demonstrating string functions, among others. Additionally, it covers data structures like stacks, file operations, regular expressions, lists, dictionaries, exception handling, and data visualization with Matplotlib.

Uploaded by

nandeesh262371
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/ 14

PYTHON LAB MANUAL

Mr. Varun K S
Mrs. Usha N
L

PART - A

1. Program to check if a number belongs to the Fibonacci Series.


n = int(input("Enter the values:"))
fib1 = 0
fib2 = 1
fib3 = 0
if n==0 or n==1:
print ("Given number is fibnocci.")
else:
while fib3<=n:
fib3=fib1+fib2
fib1=fib2
fib2=fib3
if fib3==n:
print ("{} is a fibnocci series".format(n))
exit()
else:
print("{} is not a fibnocci series".format(n))
Output

2. Program to solve Quadratic Equation.


import math
elements = []
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
c = int(input("Enter value for c"))
if a==0:
x=-b/c
print("The only root is x",x)
exit()
d=b*b-4*a*c
if d>0:
print("Real and Distinct roots are:")
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)

2 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

print("x1 = %7.3f"%(x1))
print("x2 = %7.3f"%(x2))
elif d==0:
print("Repeated roots are:")
x1=-b/(2*a)
x2=x1
print("x1 and x2 = %7.3f "%(x1))

else:
d=math.sqrt(abs(d))
rpart = -b/(2*a)
ipart = d/(2*a)
print("Complex roots are")
print("x1 = %7.3f+i%7.3f"%(rpart,ipart))
print("x2 = %7.3f-i%7.3f"%(rpart,ipart))

Output

3. Program to find sum of n natural numbers.


num1 = int(input("Enter start range"))
num2 = int(input("Enter end range"))
sum=0
if num1<num2:
if num1<=0:
print("Please enter valid start range")
else:
print("Natural numbers are")
for i in range(num1,num2+1 ):
sum+=i

3 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

print(i)
print(f"Sum of natural number is {sum} ")
else:
print("Start range number should be less than end range number")
Output

4. Program to display Multiplication Tables.


num = int(input("Enter a number to print tables: "))
for i in range(1,11):
print("{} * {} = {}".format(num,i,(i*num)))
Output

5. Program to check if a given number is Prime or not.


num = int(input("Enter the number"))
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

4 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

Output

6. Program to implement a sequential search.


size = int(input("Enter the size"))
print(f"Enter",size,"elements")
ele = []
for i in range(size):
ele.append(input())
print("Enter the element you want to search")
search_ele = input()
if search_ele in ele:
print("Element found at",ele.index(search_ele),"Index")
else:
print("Element not found")
Output

Output : - 2

5 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

7. Program to create calculator program.


def add():
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
print(f"Addition of {a} and {b} is",a+b)
print(" ")

def sub():
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
print(f"subtraction of {a} and {b} is",a-b)
print(" ")

def mul():
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
print(f"Multiplication of {a} and {b} is",a*b)
print(" ")

def quo():
try:
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))
print(f"Division of {a} and {b} is",a/b)
print(" ")
except:
print("Cannot divide by zero, Please enter different number")
print(" ")

while True:
print("Simple Calculator Program")
print("**************************")
print(" 1:Addition\n 2:Subtraction\n 3:Multiplication \n 4:Division \n 5:Exit")
res = int(input("Enter you choice"))
if res == 1:
add()
elif res == 2:
sub()
elif res == 3:
mul()
elif res == 4:
quo()
elif res == 5:
exit()
else:
print("Please enter valid number")
print("****************************")

6 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

Output

8. Program to explore string functions.


message = "GMS Academy First Grade College"
print("Split:- ", message.split())
print("Uppercase:-" ,message.upper())
print("Lowercase:-" ,message.lower())
print("Index of the search string",message.find("face"))

message1 = "GMS Academy First Grade College,Dvg"


print(message1)
print("Replaced string:-" ,message1.replace("Dvg","Davangere"))

message2 = "GMS Academy First Grade Colleges"


print("Title:-" ,message2.title())

Output

7 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

Split:- ['GMS', 'Academy', 'First', 'Grade', 'College']


Uppercase:- GMS ACADEMY FIRST GRADE COLLEGE
Lowercase:- gms academy first grade college Index of the
search string -1
GMS Academy First Grade College,Dvg
Replaced string:- GMS Academy First Grade
College,Davangere Title:- Gms Academy First Grade
Colleges

PART-B

1. Program to implement selection sort.


def selectionSort(ele, size):
for i in range(size):
min_index = i
for j in range(i + 1, size):
if ele[j] < ele[min_index]:
min_index = j
(ele[i], ele[min_index]) = (ele[min_index], ele[i])
num = int(input("Enter the size"))
print(f"Enter",num,"elements")
elements = []
for i in range(num):
elements.append(input())
selectionSort(elements,num)
print("Element after sorting in Ascending order")
print(elements)
Output

8 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

2. Program to implement stack.


def push():
if len(letters) > size-1:
print("*****Stack is full*****")
else:
ele = input("Enter the element you want to add")
letters.append(ele)
print("Element added successfully")
def pop():
if len(letters) == 0:
print("*****Stack is empty*****")
else:
letters.pop()
print("Element deleted successfully")
def display():
if len(letters) == 0:
print("*****Stack is empty*****")
else:
print("elements in stack")
print(letters)

letters=[]
size = int(input("Enter the size of the stack"))
while True:
print("Operations on stack")
print("1.Push\n2.Pop\n3.display\n4.Exit")
choice = int(input("Enter your choice"))
if choice==1:
push()
elif choice ==2:
pop()
elif choice == 3:
display()
elif choice == 4:
exit()
else:
print("Please enter valid choice")
Output

9 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

10 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

3. Program to read and write the file.


f = open("test1.txt",'r+')
f.write("GMS Academy First Grade College")
f.write("\n GMIT Campus, Davangere")
print("Content written to file")
print("****************************")
print("Content within file")
print(f.readlines())
f.close()
Output:

Content written to file


****************************
Content within file
['GMS Academy First Grade College\n', ' GMIT Campus, Davangere']

4. Program to check the given number is palindrome or not.


str = str(input("Enter the number or string to check whether it is palindrome or not "))
str1 = str[::-1]
if str == str1:
print("Entered input is palindrome")
else:
print("Entered input is not palindrome")
Output:

5. Program to demonstrate usage of basic regular expression.


import re
pattern = r"College"
text = "GMS Academy First Grade College,Dvg"
find = re.search(pattern, text)
if find:
print("Pattern found!")
else:
print("Pattern not found.")
old_text = 'Dvg'
replacement = "Davangere"
new_text = re.sub(old_text, replacement, text)
print(f"Old_text:{text}")
print(f"Modified text: {new_text}")
Output :
Pattern found!
Old_text:GMS Academy First Grade College,Dvg
Modified text: GMS Academy First Grade College,Davangere

11 Varun K S, Asst Prof. GMSAFGC


Usha N, Asst Prof. GMSAFGC
L

6. Program to demonstrate use of list.


lst1 = [9,1,6,4,23,74]
print(f"Displaying list elements:- {lst1}")
lst1.append(6)
print(f"Adding one element to the list:- {lst1}")
lst1.pop()
print(f"Deleting one element from the list:- {lst1}")
lst1.sort()
print(f"Sorting of list elements{lst1}")
lst1.reverse()
print(f"Reversing of a list:- {lst1}")
print(f"Maximum element inside a list {max(lst1)}")
print(f"Minimum element inside a list {min(lst1)}")
Output

7. Program to demonstrate use of Dictionaries.


dict1 = {1:'G',2:'M',3:'S',4:'A'}
print(f"Accessing complete dictionary {dict1}")
print(f"Accessing only {dict1.keys()}")
print(f"Accessing only {dict1.values()}")
dict1.update({5:'D',6:'V',7:'G'})
print(f"Updating Dictionary elements:- {dict1}")
del dict1[4]
print("Deleting single element from the dictionary:-",dict1)
dict1.clear()
print(f"clear() function is used to clear an entire dictionary:- {dict1}")
Output

12 Varun K S, Asst Prof. GMSAFGC


L

8. Program to demonstrate Exceptions in python.


try:
print("Division of two numbers")
a = int(input("Enter value for A"))
b = int(input("Enter value for B"))
result = a/b
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter Numeric values")
else:
print("Program executed Successfully")

Output:- 1 Output:-2

9. Program to drawing Line chart and Bar chart using Matplotlib


a. Line Chart
import matplotlib.pyplot as plt
x = ['2018','2019','2020','2021','2022']
y = [0,5000,4500,6000,4000]

plt.title("Number of Cars sold per year")


plt.xlabel("Year")
plt.ylabel("Number of units sold")

plt.plot(x,y,"*--r")
plt.show()

Output

13 Varun K S, Asst Prof. GMSAFGC


L

b. Bar Chart
import matplotlib.pyplot as plt
import numpy as np
x= ["Physics","Chemistry","Maths","Computer_Science"]
y= [4,3,5,6]
female = [2,1,3,3]
male = [2,2,2,3]
X_axis = np.arange(len(x))

plt.title("Total No of employee in a ABC college")


plt.xlabel("Department")
plt.ylabel("No of employees")
plt.xticks(X_axis,x)
plt.bar(x,y,width=0.2,color="grey",label = "Total employees")
plt.bar(X_axis - 0.2,female,width=0.2,color="pink",label = "Female")
plt.bar(X_axis - 0.4,male,width=0.2,color="blue",label = "Male")
plt.legend()
plt.show()
Output

14 Varun K S, Asst Prof. GMSAFGC

You might also like