You are on page 1of 73

Pgm.

No:1
1.Fibonacci Series
08/06/2023

AIM:
To write a python program to generate Fibonacci series using function.

CODE:
n = int(input("Enter the value of 'n': "))
a=0
b=1
c=0
count = 1

if n>1:
print("Fibonacci Series: ")
while(count <= n):
print("element",count,"in fibonacci series is",c)
a=b
b=c
c=a+b
count += 1
else:
print("Invalid input")
OUTPUT:
Pgm.No:2
2.Pascal’s Triangle
09/06/2023

AIM:
Program to print Pascal’s triangle

CODE:
a = int(input("Enter number(1-5): "))
for i in range(a):
print(" "*(a-i),end = "")
print(" ".join(map(str,str(11**i))))
OUTPUT:
Pgm.No:3
3.Creating and Searching in
14/06/2023
Dictionaries

AIM:
To create a dictionary to store roll numbers and name of students, for a
given roll number display the corresponding name else display appropriate
error message.

CODE:
def create_dic():
global dict
dict = {}
num = int(input("Enter the no.of student entries: "))
for i in range(1,num+1):
print("Enter roll num of student",i,":",end = '')
roll = int(input())
print("Name of the student: ",end = '')
name = input()
dict[roll] = name
return dict

def search_dic():
global dict
roll = int(input("Roll num to search: "))
for i in dict.keys():
if roll == i:
print(i,':',dict[i])
else:
continue

def main():
while True:
print("1)Create dictionary")
print("2)Search dictionary")
print("3)Exit")
choice = int(input("Enter choice: "))

if choice == 1:
create_dic()
elif choice == 2:
search_dic()
elif choice == 3:
break
else:
print("ERROR!!")
main()

main()
OUTPUT:
Pgm.No:4
21/06/2023
4.Number Comparison

AIM:
Program that takes two number and prints the number with lowest
one’s place.

CODING:
def comparing(a,b):
p = a%10
l = b%10
if p>l:
print(b,"has smaller one's place num")
elif l>p:
print(a,"has smaller one's place num")
else:
print("both",a,b,"has same one's place")

a = int(input("enter a: "))
b = int(input("enter b: "))
comparing(a,b)
OUTPUT:
Pgm.No:5
30/06/2023
5.Calculate Area of different shapes

AIM:
To calculate area of different shapes (menu driven program)

CODING:
def circle():
r = float(input("radius: "))
print("area: ",22/7*r**2,"cm2")

def sq():
s = float(input("side: "))
print("area: ",s**2,"cm2")

def rec():
l = float(input("length: "))
b = float(input("breath: "))
print("area: ",l*b,"cm2")

def tri():
b = float(input("base: "))
h = float(input("height: "))
print("area: ",1/2*b*h,"cm2")

while True:
print("1. area of square")
print("2. area of rectangle")
print("3. area of triangle")
print("4. area of circle")
print("5. Exit")
print()
val = int(input("Which you need to find: "))

if val == 1:
sq()
print()
elif val == 2:
rec()
print()
elif val ==3:
tri()
print()
elif val == 4:
circle()
print()
elif val == 5:
break
else:
print("!!Type properly bro!!")
print()
OUTPUT:
Pgm.No:6
10/07/2023
6.Random Number Generation

AIM:
To generate random numbers between 1-6 (dice game)

CODING:
import random
while True:
n = int(input("Enter your number(1-6): "))
i = random.randint(1,6)
print("Generated number: ",i)
if i==n:
print("Win!")
elif i!=n:
print("Lost")
else:
print("invalid input")
OUTPUT:
Pgm.No:7
7. Character Categorization
11/07/2023

AIM:
Program to count alphabets, vowels, uppercase, lowercase, special
char, digits and consonants.

CODING:
def pp7():
a=v=u=l=s=d=c=0
for i in open("poem.txt","r").read():
if i.isalpha:
a+=1
if i in ["a","A","e","E","i","I","O","o","u","U"]:
v+=1
else:
c+=1
if i.isupper():
u+=1
elif i.islower():
l+=1
elif i.isdigit():
d+=1
else:
s+=1
print("Alphabets: ",a)
print("Uppercase: ",u)
print("Lowercase: ",l)
print("Vowels: ",v)
print("Digits: ", d)
print("Consonents: ",c)
print("Special char: ",s)

pp7()
OUTPUT:
Pgm.No:8
Copying specific lines
13/07/2023

AIM:
Program that copies specific lines (source.txt to target.txt).

CODING
def lines():
f = open('source.txt','r')
g = open('target.txt','w')
g_lines = []
for i in f.readlines():
if i[0] == '@':
g_lines.append(i)
g.writelines(g_lines)
f.close()
g.close()

lines()
OUTPUT:
source.txt:

target.txt:
Pgm.No:9
Operations in Text file
19/07/2023

AIM:
Program to perform
1)Display the text file content with '#'.
2)Display the lines starting with 'T'.
3)Display the number of occurances of 'is' & 'and.

CODING:

def Hashtag():
try:
f = open("text.txt",'r')
lines = f.readlines()
for i in lines:
print(i.replace(" ","#"))
except FileNotFoundError:
print("File not found")

def Printspeclines():
try:
f = open('text.txt','r')
for i in f.readlines():
if i.startswith("T"):
print(i)
except FileNotFoundError:
print("File not found")

def countIS_AND():
try:
count_is = 0
count_and = 0
f = open("text.txt",'r')
for i in f.readlines():
words = i.split()
for j in words:
if j in ['is','IS','Is']:
count_is+=1
elif j in ["And",'and','AND']:
count_and+=1
print("No of 'is': ",count_is)
print("No of 'and': ",count_and)
except FileNotFoundError:
print("File not found")

while True:
print("\n")
print("1)Display content (#)")
print("2)Display lines which start with 'T'")
print("3)Diplay number of occurances of 'is' & 'and'")
print("4)Exit")
choice = int(input("\nEnter choice: "))

if choice == 1:
Hashtag()
elif choice == 2:
Printspeclines()
elif choice == 3:
countIS_AND()
elif choice == 4:
break
else:
print("Invalid Input")
OUTPUT:

text.txt
Pgm.No:10
Store and search data in
dictionary(binary)
26/07/2023

AIM:
To store and search data in dictionary(binary file)

CODING:
from pickle import dump,load
member_data = {}
def store_data():
global member_data
try:
f = open("data.bin",'ab')
n = int(input("Enter number of records to store: "))
for i in range(1,n+1):
member_no = int(input("Enter Member Number ({0}):
".format(i)))
member_name = input("Enter Member Name ({0}):
".format(i))
member_data[member_no] = member_name
dump(member_data,f)
except FileNotFoundError:
print("File not found")

def search_data():
try:
f = open("data.bin",'rb')
count = 0
mem_num = int(input("Enter Member Number to search: "))
a = load(f)
for i in a.keys():
if i == mem_num:
print("{0}:{1}".format(i,a[i]))
count+=1
else:
if count == 0:
print("No matching records found")
except FileNotFoundError:
print("File not found")

while True:
print("\n")
print("1)Store data")
print("2)Search data")
print("3)Exit")
choice = int(input("Enter choice(1-3): "))

if choice == 1:
store_data()
elif choice == 2:
search_data()
elif choice == 3:
break
else:
print("Invalid input!")
OUTPUT:
Pgm.No:11
Updating data in binary files
09/08/2023

AIM:
Program which takes employee number and updates salary.

CODING:
from pickle import load,dump
def increase():
try:
with open("emp_data.dat",'rb') as f:
emp_data = load(f)
print(emp_data)
f = open("emp_data.dat",'wb')
n = int(input("Enter emp num to increase salary: "))
h_salary = int(input("Enter how much the current salary to be
increased by: "))
for i in emp_data:
if i == n:
c_name = emp_data[i][0]
c_salary = emp_data[i][1]
emp_data[i] = [c_name,c_salary+h_salary]
dump(emp_data,f)
print("Updated")
print("Old salary: ",c_salary)
print("New salary: ",c_salary+h_salary)
f.close()
except FileNotFoundError:
print("File not found")

increase()
OUTPUT:
Pgm.No:12
Operations in Binary files
11/08/2023

AIM:
Program to read/write/update and append data in binary files.

CODING:
from pickle import load,dump
from os import remove,rename
member_data = {}
def read():
try:
with open("data.bin",'rb') as f:
try:
while True:
a = load(f)
except EOFError:
pass
print("{:<10} {:<15}".format("Member No","Member
Name"))
for i in a.keys():
print("{:<11} {:<15}".format(i,a[i]))
except FileNotFoundError:
print("File not found")

def write():
with open('data.bin','wb') as f:
number = int(input("Enter no of records to enter: "))
for i in range(1,number+1):
mem_no = int(input("Enter Member Number: "))
mem_name = input("Enter Member Name: ")
member_data[mem_no] = mem_name
dump(member_data,f)

def update():
try:
with open('data.bin','rb') as f:
up_num = int(input("Enter member number to update: "))
try:
while True:
a = load(f)
except EOFError:
pass
for i in a.keys():
n=0
if i == up_num:
old_no = i
old_name = a[i]
new_name = input("Enter New Name: ")
a[i] = new_name
print("Old record: {0} {1}".format(old_no,old_name))
print("Updated record: {0} {1}".format(i,a[i]))
with open('data.bin','wb') as f:
dump(a,f)
except FileNotFoundError:
up_num = int(input("Enter member number to update: "))
try:
while True:
a = load(f)
except EOFError:
pass
for i in a.keys():
n=0
if i == up_num:
old_no = i
old_name = a[i]
new_name = input("Enter New Name: ")
a[i] = new_name
print("Old record: {0} {1}".format(old_no,old_name))
print("Updated record: {0} {1}".format(i,a[i]))
with open('data.bin','wb') as f:
dump(a,f)
except FileNotFoundError:
else:
print("Invalid Input!")
OUTPUT :
Pgm.No:13
To store and retrieve data from csv file
14/08/2023

AIM:
Program to store and retrieve data from csv file.

CODING:
import csv as c
def store():
global f
try:
f = open("student_info.csv",'w',newline = "")
w = c.writer(f)
n = int(input("Enter number of student details to enter: "))
for i in range(1,n+1):
name = input("\nEnter name of student {0}: ".format(i))
marks = input("Enter total marks (/500): ")
w.writerow([i,name,marks])
f.close()
except FileNotFoundError:
print("File not found")

def retrive():
global f
try:
f = open("student_info.csv",'r')
r = c.reader(f)
print("{:<6} {:<18} {:<5}".format("SNo","Name","Mark"))
for i in r:
print("{:<6} {:<18} {:<3}".format(i[0],i[1],i[2]))
f.close()
except FileNotFoundError:
print("File not found")

while True:
print("\n1)Store data")
print("2)Retrive data")
print("3)Exit")
choice = int(input("Enter choice(1-3): "))

if choice == 1:
store()
elif choice == 2:
retrive()
elif choice == 3:
break
else:
print("Invalid Input!")
OUTPUT:
Pgm.No:14
22/08/2023
To copy data using delimiter

AIM :
Program to store and retrieve data from csv file.

CODING :

import csv as c

def store():
global f
try:
f = open("student_info.csv",'w',newline = "")
w = c.writer(f)
n = int(input("Enter number of student details to enter: "))
for i in range(1,n+1):
name = input("Enter name of student {0}: ".format(i))
marks = input("Enter total marks (/500): ")
w.writerow([i,name,marks])
f.close()
except FileNotFoundError:
print("File not found")
def retrive():
global f
try:
f = open("student_info.csv",'r')
r = c.reader(f)
print("{:<6} {:<18} {:<5}".format("SNo","Name","Mark"))
for i in r:
print("{:<6} {:<18} {:<3}".format(i[0],i[1],i[2]))
f.close()
except FileNotFoundError:
print("File not found")

while True:
print("\n1)Store data")
print("2)Retrive data")
print("3)Exit")
choice = int(input("Enter choice(1-3): "))
if choice == 1:
store()
elif choice == 2:
retrive()
elif choice == 3:
break
else:
print("Invalid Input!")
OUTPUT :

student_info.csv

Pgm.No:15
To copy data using delimiter
28/8/2023

AIM :
Program to copy data from one csv file to another using another delimiter and
displaying it.

CODING :
import csv

def store_data():
content = []
a = open("input_data.csv",'r')
b = open("output_data.csv",'w',newline="")
a_reader = csv.reader(a)
b_writer = csv.writer(b,delimiter = "#")
content = [i for i in a_reader]

print("Content in input_data.csv: \n")

for i in content:
print(i)

for i in content:
b_writer.writerow(i)

b.close()
a.close()
def display_data():
b = open("output_data.csv",'r')
b_writer = csv.reader(b)

content = [i for i in b_writer]

print("\nContent in output_data.csv: \n")

for i in content:
print(i[0])

store_data()
display_data()
OUTPUT :

input_data.csv

output_data.csv

Pgm.No:16
1/9/2023 Formatting output
AIM :
Program to store and retrieve formatted sports’ performance(csv file)

CODING:

import csv as c

def store():
global f
try:
f = open("data.csv",'w',newline = "")
w = c.writer(f,delimiter = "\t")
n = int(input("Enter number of records to enter: "))
for i in range(1,n+1):
s_name = input("\nEnter name of Sport {0}: ".format(i))
comp = input("Enter no.of competitions participated: ")
prizes = int(input("Enter no.of prizes won: "))
w.writerow([i,s_name,comp,prizes])
f.close()
except FileNotFoundError:
print("File not found")

def retrive():
global f
try:
f = open("data.csv",'r')
r = c.reader(f,delimiter = "\t")
print("="*50)
print("|{:^5} {:^15} {:^13} {:^11} |".format("SNo","Sport
Name","Competitions","Prizes won"))
print("="*50)
for i in r:
print("|{:^5} {:^15} {:^13} {:^11} |".format(i[0],i[1],i[2],i[3]))
print("="*50)
f.close()
except FileNotFoundError:
print("File not found")

while True:
print("\n1)Store data")
print("2)Retrive data")
print("3)Exit")
choice = int(input("Enter choice(1-3): "))
if choice == 1:
store()
elif choice == 2:
retrive()
elif choice == 3:
break
else:
print("Invalid Input!")

OUTPUT :
data.csv

Pgm.No:17
7/9/2023 Push and pop operations in stack
AIM :
Program to Push and Pop items in stack.

CODING :

book = []

def Addnew(item, book):


book.append(item)
print("Book added!")

def Remove(book):
if book == []:
print("Stack Empty!")
else:
item = book.pop()
print("{} removed!".format(item))

while True:
print("1) Add Book")
print("2) Remove Book")
print("3) Exit")

ch = int(input("Enter choice: "))

if ch == 1:
item = input("Enter Book Name: ")
Addnew(item, book)
elif ch == 2:
Remove(book)
elif ch == 3:
break
else:
print("Invalid Input")

OUTPUT :
Pgm.No:18
20/9/2023 Peek and display operations in stacks
AIM :
Program to Peek and Display items in stack.

CODING :

def Push(item, stack):


stack.append(item)
top = len(stack) - 1

def Display(stack):
top = len(stack) - 1
print(stack[top] ,"<-top")
for i in range(top-1, -1, -1):
print(stack[i])

def Peek(stack):
if stack == []:
print("Undeflow")
else:
top = len(stack) - 1
return stack[top]

stack = []
top = None

while True:
print("1)Push")
print("2)Display")
print("3)Peek")
print("4)Exit")

ch = int(input("Enter choice: "))

if ch == 1:
bookno = input("Enter Book Number: ")
bookname = input("Enter Book Name: ")
Push([bookno, bookname], stack)
print("Book Added!")
elif ch == 2:
Display(stack)
elif ch == 3:
print(Peek(stack))
elif ch == 4:
break
else:
print("Invalid Input!")

OUTPUT :
Pgm.No:19
3/10/2023 Stack implementation

AIM :
Program to implement a stack and its operations.

CODING :

def isEmpty(stack):
if stack == []:
return True
else:
return False

def Push(item, stack):


stack.append(item)
top = len(stack) - 1

def Pop(stack):
item = stack.pop()
if isEmpty(stack):
print("\nStack Empty")
else:
if len(stack) == 0:
top = None
else:
top = len(stack) - 1
return item

def Display(stack):
top = len(stack) - 1
print(stack[top] ,"<-top")
for i in range(top-1, -1, -1):
print(stack[i])

def Peek(stack):
if isEmpty(stack):
print("Undeflow")
else:
top = len(stack) - 1
return stack[top]

stack = []
top = None

while True:
print("1)Push")
print("2)Pop")
print("3)Display")
print("4)Peek")
print("5)Exit")

ch = int(input("Enter choice: "))

if ch == 1:
bookno = input("Enter Book Number: ")
bookname = input("Enter Book Name: ")
Push([bookno, bookname], stack)
print("Book Added!")
elif ch == 2:
print("Item popped: ", Pop(stack))
elif ch == 3:
Display(stack)
elif ch == 4:
print(Peek(stack))
elif ch == 5:
break
else:
print("Invalid Input!")

OUTPUT :
SQL Commands

PGM NO 20
6/11/2023 SQL COMMANDS

a) Create:
COMMAND :

CREATE TABLE students (


Sno INT,
AdNo INT PRIMARY KEY,
Name CHAR(20),
Gender CHAR(1),
DOB DATE,
Percentage FLOAT
);

b) Alter :
c) Update :

d) Order By :
e) Delete :

f) Group By :

g) Joins :
Python Database Connectivity

Pgm.No:21
2/11/2023 CONNECTIVITY - 1

AIM :
To display data of a table from sql database in Python

CODING :

import mysql.connector as a

b = a.connect(host="localhost", user="root", passwd='root', database='jk')


c = b.cursor()
c.execute("SELECT * FROM students")
results = c.fetchall()
for i in results:
print(i)

print("\nTotal records: ", c.rowcount)

OUTPUT :

SQL OUTPUT :
PYTHON OUTPUT :

Pgm.No:22
6/11/2023 CONNECTIVITY - 2

AIM :
To display data of a table from sql database with rowcount in Python.
CODING :

import mysql.connector as a
b = a.connect(host="localhost", user="root", passwd='root', database='jk')
c = b.cursor()
c.execute("select * from emp")
for i in range(5):
data = c.fetchone()
print("Record {0}: {1}".format(c.rowcount, data))

OUTPUT :

SQL OUTPUT :
PYTHON OUTPUT :

Pgm.No:23
CONNECTIVITY-3
8/11/2023

AIM:
To insert a record in sql database using Python.

CODING:
import mysql.connector as a
con = a.connect(host="localhost", user="root", passwd='root',
database='emp')
if con.is_connected():
cur=con.cursor()
opt='y'
while opt=='y':
No=int(input("enter emp no"))
Name=input("enter emp name")
Gender=input("enter emp gender")
sal=int(input("enter sal"))
q="insert into emp1
values({},'{}','{}',{})".format(No,Name,Gender,sal)
cur.execute(q)
con.commit()
print("rec stored")
opt=input("do you want to add another det(y/n)")
q="select * from emp1";
cur.execute(q)
data=cur.fetchall()
for i in data:
print(i)
con.close()
OUTPUT:
SQL TABLE:
BEFORE:
AFTER:

PYTHON OUTPUT :

Pgm.No:24
CONNECTIVITY-4
15/11/2023
AIM:
To update and delete a record in sql database using Python.

CODING:
import mysql.connector as a

b = a.connect(host="localhost", user="root", passwd='root',


database='sample')
c = b.cursor()

update_cmd = "UPDATE emp SET salary = 200 WHERE department = 'CEO'"


delete_cmd = "DELETE FROM emp WHERE department='Janitor'"

c.execute(update_cmd)
b.commit()

c.execute(delete_cmd)
b.commit()

OUTPUT:
SQL TABLE:
BEFORE:
AFTER:

You might also like