0% found this document useful (0 votes)
4 views

PYTHON_LAB_MANUAL[1]

The document contains a series of Python programming exercises covering various topics such as Fibonacci sequence checking, solving quadratic equations, natural number summation, multiplication tables, prime number checking, linear search, calculator implementation, string functions, selection sort, stack implementation, file operations, regular expressions, list and dictionary usage, SQLite database operations, GUI creation with Tkinter, exception handling, and data visualization with Matplotlib and NumPy. Each exercise includes code snippets and explanations for functionality. The document serves as a comprehensive guide for practicing Python programming skills.

Uploaded by

junaidpasha1997
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

PYTHON_LAB_MANUAL[1]

The document contains a series of Python programming exercises covering various topics such as Fibonacci sequence checking, solving quadratic equations, natural number summation, multiplication tables, prime number checking, linear search, calculator implementation, string functions, selection sort, stack implementation, file operations, regular expressions, list and dictionary usage, SQLite database operations, GUI creation with Tkinter, exception handling, and data visualization with Matplotlib and NumPy. Each exercise includes code snippets and explanations for functionality. The document serves as a comprehensive guide for practicing Python programming skills.

Uploaded by

junaidpasha1997
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PART A

1) Check if a number belongs to the Fibonacci Sequence


n=int(input("Enter a no:"))
a=0
b=1
while b<n:
c=a+b
a=b
b=c
if b==n or a==n:
print ("Fibonacci Number")
else:
print("Not a Fibonacci Number")

2)Solve Quadratic equations


print("Equation:ax^2+bx+c")
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
c=int(input("Enter c value:"))
d=b**2-4*a*c
d1=d**0.5
if d<0:
print("Complex roots")
elif d==0:
r=-b/(2*a)
print("Real and same roots",r)
else:
print("Real and different roots")
r1=(-b+d1)/2*a
r2=(-b+d1)/2*a
print("First root",r1)
print("Second root",r2)

3)Find the sum of n natural numbers


n=int(input("Enter the number:"))
sum=0
for i in range(1,n+1):
sum+=i
print(f"The sum is{sum}")
4)Display multiplication Tables
n=int(input("Enter any number to print the multiplication table:"))
print(" The multiplication table of:",n)
for i in range(1,11):
print(n,'x',i,'=',n*i)

5)Check if a given number is a prime number or not

n=int(input("Please enter any number:"))


c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
if c==2:
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")

6)Implement Sequential search

def linear_search(a,n,key):
for i in range(0,n):
if(a[i]==key):
return i
return -1
a=[1,3,5,4,7,9]
print(a)
key=int(input("Enter the number to search:"))
n=len(a)
res=linear_search(a,n,key)
if(res==-1):
print(f"Elements not found")
else:
print("Elements found at index:",res)
7)Create a calculator program

def calc(n1,n2,op):
if op=='+':
r=n1+n2
elif op=='-':
r=n1-n2
elif op=='*':
r=n1*n2
elif op=='/':
r=n1/n2
elif op=='^':
r=n1**n2
else:
print("Invalid operator")
return r
n1=float(input("Enter 1st number:"))
n2=float(input("Enter 2nd number:"))
op=input("Enter the operator(+,-,*,/,^)")
r=calc(n1,n2,op)
print(f"{n1} {op} {n2}={r}")

8)Explore String functions

text='hello'
print("converted string to uppercase:")
print(text.upper())

print("converted string to lowercase:")


print(text.lower())

print("string in title format:")


print(text.title())

print("string first character to uppercase:")


print(text.capitalize())

print("number of occurance of 1")


print(text.count("1"))
print("first occurance of lo")
print(text.find("lo"))
print("string ends with e or not :",text.endswith("lo"))
print("string character are in lowercase or not:",text.islower())
print("string character in uppercase or no:",text.isupper())
print("string character digits or not:",text.isdigit())

9)Implement selection sort

def selec(a,size):
for i in range(size):
min=i
for j in range(i+1,size):
if a[j]<a[min]:
min=j
a[i],a[min]=a[min],a[i]
a=[-2,45,0,11,-9]
print(f"before sorting {a}")
size=len(a)
selec(a,size)
print(f"after sorting {a}")

10)Implement stack

stack=[]
size=3
def display():
print("stack elements are")
for item in stack:
print(item)
def push(item):
print(f"push on item to stack:{item}")

if len (stack)<size:
stack.append(item)
else:
print("stack is full")
def popitem():

if len(stack)>0:
print(f"pop an item from stack:{stack.pop()}")
else:
print("stack is empty")
push(10)
push(20)
push(30)
display()
push(40)
popitem()
display()
popitem()
popitem()
popitem()

11)Read and write into a file

file=open("myfile test.text", "w")


l=["this is python \n","this is file \n"]

file.write("hello there\n")
file.writelines(l)
file.close()

file=open("myfile test.text", "r")


print("output of read function is")
print(file.read())

file.seek(0)
print("out of readline function is")
print(file.readline())

file.seek(0)
print("output of readlines function is")
print(file.readlines())
PART B

1)Demonstrate use of basic regular expression


import re
string="Rahul salary is 50000"
res = re.findall("[a-m]", string)
print(res)
res=re.search(r"\d", string)
print(res)
res=re.search('[^0-9]', '123abc')
print(res)
res=re.findall(r"\d", string)
print(res)
res=re.split(r"\s", string)
print(res)
res=re.sub(r"\s","-", string)
print(res)

2)Demonstrate use of advanced regular expression for data


validation
import re
def validate_password(password):
pattern = r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$"
match = re.match(pattern, password)
return bool(match)

pswd=input("enter password:")
res=validate_password(pswd)
if res:
print("valid password")
else:
print("Invalid password")
3)Demonstrate use of List
list=[10,40,20,50,30]
print("first element:",list[0])
print("fourth element:",list[3])
print("list element from 0 to 2 index:", list[0:3])
list.append(20)
print('list after append:',list)
print("index of 20",list.index(20))
list.sort()
print("list after sorting",list)
print("popped element is:",list.pop())
print("list after pop",list)
list.insert(2,50)
print("list after insert:",list)
print("number of occurence of 50:",list.count(5))
list.remove(10)
print("list after removing 10:",list)
list.reverse()
print("list after reversing:",list)

4)Demonstrate use of Dictionaries

boxoffice={}
for i in range(0,4):
key=input("enter key:")
value=input("enter value:")
boxoffice[key]=value
print(boxoffice)
print("length of dictionary:",len(boxoffice))
boxoffice["avatar"]=2009
print("dictionary after modification:",boxoffice)
print("titanic is present:","titanic" in boxoffice)
print("titanic was released in the year:",boxoffice.get("titanic",1997))
print("dictionary keys are:",boxoffice.keys())
print("dictionary values are:",boxoffice.values())
print("pop item from dictionary",boxoffice.popitem())
boxoffice.setdefault("harrypotter",2011)
print("after setting harrypotter:",boxoffice)
boxoffice.update({"frozen":2013})
print("after inserting new item",boxoffice)

5)Create SQLite database and perform operations on table


import sqlite3
conn = sqlite3.connect('test.db')
print ("Opened database successfully");
conn.execute('''CREATE TABLE STUDENT
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL);''')
print ("Table created successfully");
conn.execute("INSERT INTO STUDENT (ID,NAME,AGE) \
VALUES (1, 'Ram', 20)");
conn.execute("INSERT INTO STUDENT (ID,NAME,AGE) \
VALUES (2, 'Jon', 19)");
conn.execute("INSERT INTO STUDENT (ID,NAME,AGE) \
VALUES (3, 'Maya', 18)");
conn.commit()
print ("Records created successfully");
cursor = conn.execute("SELECT id, name, age from STUDENT")
for row in cursor:
print ("ID = ", row[0])
print ("NAME = ", row[1])
print ("AGE = ", row[2],"\n")

print ("Operation done successfully");


conn.execute("UPDATE STUDENT set AGE = 25 where ID = 1")
cursor = conn.execute("SELECT id, name, age from STUDENT")
for row in cursor:
print ("ID = ", row[0])
print ("NAME = ", row[1])
print ("AGE = ", row[2],"\n")
print ("Updated table successfully");
conn.commit()
conn.close()
6)Create a GUI using TKinter module
from tkinter import *
class MyWindow:
def __init__(self, win):
self.lbl1=Label(win, text='First number')
self.lbl2=Label(win, text='Second number')
self.lbl3=Label(win, text='Result')
self.t1=Entry(bd=3)
self.t2=Entry()
self.t3=Entry()

self.btn1 = Button(win, text='Add')


self.btn2=Button(win, text='Subtract')

self.lbl1.place(x=100, y=50)
self.t1.place(x=200, y=50)

self.lbl2.place(x=100, y=100)
self.t2.place(x=200, y=100)

self.b1=Button(win, text='Add', command=self.add)


self.b2=Button(win, text='Subtract')
self.b2.bind('<Button-1>', self.sub)

self.b1.place(x=100, y=150)
self.b2.place(x=200, y=150)

self.lbl3.place(x=100, y=200)
self.t3.place(x=200, y=200)

def add(self):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1+num2
self.t3.insert(END, str(result))
def sub(self, event):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1-num2
self.t3.insert(END, str(result))
window=Tk()
mywin=MyWindow(window)
window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()

7)Demonstrate Exception in python

a=int(input("enter first number:"))


b=int(input("enter second number:"))
try:
c=a/b
except:
print("division by zero not possible")
else:
print("answer=",c)
finally:
print("end of the program")

8)Drawing Line chart and bar chart using Matplotlib


import matplotlib.pyplot as plt
country = ['A','B','C','D','E']
gdp=[45000,42000,55000,52000,65000]
plt.bar(country, gdp, color ='red')
plt.title('Country Vs GDP Per Capita')
plt.xlabel('Country')
plt.ylabel('GDP Per Capita')
plt.plot(country, gdp)
plt.show()
9)Drawing Histogram and Pie chart using Matplotlib

Histogram
import matplotlib.pyplot as plt
marks=[65,50,34,90,26,97,56,67,45,95]
grade=[0,35,70,100]
plt.xticks([0,35,70,100])
plt.hist(marks,grade,facecolor="g")
plt.xlabel("Percentage")
plt.ylabel("No.of Students")

Pie chart
from matplotlib import pyplot as plt
import numpy as np
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
fig = plt.figure(figsize=(10, 7))
plt.pie(data, labels=cars)
plt.show()

10)Create array sing NumPy and perform operations on array

import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5,6])
c = np.array([[1, 2, 3,4,5], [6,7,8,9,10]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[10, 20, 30], [40, 50, 60]]])
print("Dimension of array a",a.ndim)
print("Dimension of array d",d.ndim)
print("No of elements in each dimension of array c",c.shape)
print("Different types of arrays")
print(a)
print(b)
print(c)
print(d)

e=np.arange(2, 10)
print(e)

print("array after addition",b[2] + b[3])


print("Array after slicing")
print(d[1, 1, 2])
print(c[1, 1:4])
print("Array after copying")

x = b.copy()
y = b.view()

print(x.base)
print(y.base)
print("b array after reshaping")
newarr = b.reshape(2, 3)
print(newarr)

m = np.array([[1, 2], [3, 4]])


n = np.array([[5, 6], [7, 8]])
o = np.concatenate((m, n), axis=1)
print("Array after concatinatoin",o)
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
new= np.array_split(arr, 3)
print("array after splitting",new)
print("Searching even indexed values from array b")
x = np.where(b%2 == 0)
print(x)

You might also like