You are on page 1of 65

Pgm:no 1

FIBONACCI SERIES
8/06/2023

AIM:
To write a python program to generate Fibonacci series

CODING:
f=int(input("Enter the limit :"))
l=[]
a=0
b=1
c=0
l.append(a)
l.append(b)
for i in range(2,f):
if a==0:
l.append(a+b)
a+=1
c+=i
l.append(c)

for i in range(len(l)):
print("Element - ",i+1,"in Fibonacci series: ",l[i])

1
OUTPUT:

2
Pgm:no 2
PASCAL’S TRIANGLE
9/06/2023

AIM:
Program to print Pascal’s triangle

CODING:
n = int(input("Enter number(1-5): "))
for i in range(n):
print(" "*(n-i),end = "")
print(" ".join(str(11**i)))

OUTPUT:
3
Pgm:no 3

4
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.

CODING:
def Create_dict():
global dic
dic={}
n=int(input("Enter How much enteries: "))
for i in range(1,n+1):
print("Enter the roll number of Student",i,end=' ')
r=int(input())
print("Enter the name of Student",i,end=' ')
name=input()
dic[r]=name
return dic

def Search_dict(roll):
global dic
for i in dic.keys():
if roll == i:
print("Roll number",i,"is",dic[i])
else:
continue

5
while True:
print("1)Creating_dict")
print("2)Searching Student")
print("3)Exit")
q=int(input("Enter the number for any option: "))

if q==1:
Create_dict()

if q==2:
roll=int(input("Enter the roll number"))
Search_dict(roll)

if q==3:
break

OUTPUT:

6
Pgm:no 4

7
NUMBER COMPARISON
21/06/2023

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

CODING:
def char(y,z):
if y%10==z%10:
print("Equal number in one's place")
elif y%10<z%10:
print("The lowest number in one's place is: ",y)
elif y%10>z%10:
print("The lowest number in one's place is: ",z)

c1=int(input("Enter the a character: "))


c2=int(input("Enter the a character: "))
char(c1,c2)

OUTPUT:

8
Pgm:no 5

9
CALCULATE AREA OF DIFFERENT
30/06/2023
SHAPES

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

CODING:
def square(s):
s=s**2
print("The Area of square",s)

def rectangle(l,b):
a=0
a=l*b
print("The Area of Rectangle",a)

def triangle(b,h):
a=0
a=(1/2)*b*h
print("The Area of Triangle",a)

def circle(r):
a=0
a=3.14*(r**2)
print("The Area of Circle",a)

while True :

10
print("1) Area of Square")
print("2) Area of Rectangle")
print("3) Area of Triangle")
print("4) Area of Circle")
print("5) Exit")
z=int(input("Enter the option no: "))
if z==1:
s=int(input("Enter side: "))
square(s)
if z==2:
b=int(input("Enter breadth: "))
l=int(input("Enter lenght: "))
rectangle(l,b)
if z==3:
b=int(input("Enter breadth: "))
h=int(input("Enter height: "))
triangle(b,h)
if z==4:
r=int(input("Enter radius: "))
circle(r)
if z==5:
break

OUTPUT:

11
Pgm:no 6

12
RANDOM NUMBER GENERATION
10/07/2023

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

CODING:
import random
while True:
i=int(input("Enter the number in (1-6)"))
no=random.randint(1,6)
if i>=1 and i<=6:
if i==no:
print("The Dice Number is Matches to your Number",i,"=",no)
print("Victory!")
elif i!=no:
print("The Dice Number is not Matches to your Number",i,"!
=",no)
print("Try Again")
else:
print("Invalid Syntax")
break

OUTPUT:

13
Pgm:no 7

14
CHARACTER CATEGORIZATION
11/07/2023

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

CODING:
def Count():
o=open("TESTFILE.txt","r")
a=vc=u=l=dc=sch=c=0
v=["a","A","e","E","I","i","O","o","U","u"]
d=o.read()
for i in d:
if i.isalpha():
a+=1
if i in v:
vc+=1
else :
c+=1
if i.isupper():
u+=1
if i.islower():
l+=1
elif i.isdigit():
dc+=1

else:

15
sch+=1
print("Alphabets: ",a)
print("Upper_case: ",u)
print("Lower_case: ",l)
print("Digits: ",dc)
print("Special char: ",sch)
print("Vowels: ",vc)
print("Consonants: ",c)
o.close()

Count()

OUTPUT:

16
Pgm:no 8

17
COPYING SPECIFIC LINES
13/07/2023

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

CODING:
o=open("source.txt","r")
o1=open("target.txt","w")
s=o.readlines()
for i in s:
if i[0]=="@":
o1.write(i)
o.close()
o1.close()

OUTPUT:
source.txt

18
target.txt

Pgm:no 9

19
OPERATIONS IN TEXT FILES
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 occurrences of ‘is’ & ‘and’.

CODING:
def Hash():
try:
f=open("source.txt","r")
l=f.readline()
while l!="":
s=l.split()
l=f.readline()
for i in s:
print(i,end="#")
f.close()
except FileNOTFoundError:
print("File nor Found")

def Speclines():
try:
f=open("source.txt","r")

20
l=f.readlines()
for i in l:
if i.startswith("T"):
print(i)
f.close()
except FileNOTFoundError:
print("File nor Found")

def Count():
try:
o=open("TESTFILE.txt","r")
c=0
v=["is","and"]
d=o.read()
for i in d:
if i in v:
c+=1
print("The Count of alphabets is and and: ",c)
o.close()
except FileNOTFoundError:
print("File nor 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'")

21
print("4)Exit")

choice = int(input("\nEnter choice: "))

if choice == 1:
Hash()
elif choice == 2:
Speclines()
elif choice == 3:
Count()
elif choice == 4:
break
else:
print("Invalid Input")

OUTPUT:

22
Pgm:no 10

23
STORE AND SEARCH DATA IN
26/07/2023
DICTIONARY (BINARY)

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

CODING:
import pickle
def Store_dat():
s=open("File.dat","ab")
d={}
n=int(input("Enter no.of data going to be entered:"))
for i in range(n):
ad=int(input("Enter the admin no:"))
stu_na=input("Enter the name of Student:")
cls=input("Enter the class:")
d["Admin_no"]=ad
d["Name"]=stu_na
d["Class"]=cls
pickle.dump(d,s)
s.close()

def read_dat():
try:
s=open("File.dat","rb")
d={}
no=int(input("Enter the admin_no:"))

24
while True:
d=pickle.load(s)
if d["Admin_no"]==no:
print(d)
except:
s.close()
while True:
print("\n")
print("1)Store the data")
print("2)Search the data")
print("3)Exit")

choice = int(input("\nEnter choice: "))

if choice == 1:
Store_dat()
elif choice == 2:
read_dat()
elif choice == 3:
break
else:
print("Invalid Input")

OUTPUT:

25
Pgm:no 11

26
UPDATING DATA IN BINARY FILE
9/08/2023

AIM:
Program which takes employee number and updates salary.

CODING:
def Salary():
try:
s=open("emp.dat","rb+")
d={}
no=int(input("Enter the emp_no:"))
h=int(input("Enter the salary to be added:"))
while True:
v=s.tell()
d=pickle.load(s)
if d["emp_no"]==no:
print("Old Salary:",d["Salary"])
print("New Salary:",d["Salary"]+h)
d["Salary"]=d["Salary"]+h
s.seek(v)
pickle.dump(d,s)
except:
s.close()
Salary()

OUTPUT:

27
Pgm:no 12

28
EXCEPTION HANDLING- SQUARE
11/08/2023
ROOT

AIM:
Program to find square root of a number using try & except block

CODING:
import math
def f(x):
if x<=0:
raise ValueError("f:argument must be greater than zero")
return math.sqrt(x)+2
def g(x):
y=f(x)
print(y>2)
try:
g(1)
g(-1)
except ValueError as e:
print("argument must be only positive numbers",str(e))

OUTPUT:

29
Pgm:no 13

30
EXCEPTION HANDLING -DIVISION OF
14/08/2023
TWO NUMBERS

AIM:
To find division of two numbers by try, except block and finally clause.

CODING:
print("Learning Exceptions...")
while True:
ch=input("\nEnter N to exit: ")
if ch=="N":
break
else:
try:
num1= int(input("Enter the first number: "))
num2=int(input("Enter the second number: "))
quotient=(num1/num2)
print("Both the numbers entered were correct")
except ValueError: # to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
finally: # to be executed at the end
print("JOB OVER... GO GET SOME REST")

OUTPUT:

31
Pgm:no 14

32
TO STORE AND RETRIEVE DATA FROM
22/08/2023
CSV FILE

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

CODING:
import csv
def Store_csv():
s=open("Stu.csv","a",newline='')
w=csv.writer(s)
n=int(input("Enter no.of Student going to enter:"))
for i in range(n):
ad=input("Enter the Student's Admin_no:")
nam=input("Enter the Student's Name:")
cl=input("Enter the Student's Class:")
ma=int(input("Enter the marks of the Student:"))
w.writerow([ad,nam,cl,ma])
s.close()
def Retrive_csv():
s=open("Stu.csv","r")
r=csv.reader(s)
admi=int(input("Enter the admin no of Student:"))
for i in r:
if i[0]==str(admi):
print("Student's Detail",i)
s.close()
while True:

33
print("\n")
print("1)Store data")
print("2)Retrive data")
print("3)Exit")

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

if choice == 1:
Store_csv()
elif choice == 2:
Retrive_csv()
elif choice == 3:
break
else:
print("Invalid Input")

OUTPUT:

34
Stu.csv

Pgm:no 15

35
TO COPY DATA USING DELIMITER
28/08/2023

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

CODING:
import csv
def Store_csv():
s=open("Stu.csv","r")
o=open("Stu1.csv","w",newline='')
r=csv.reader(s)
w=csv.writer(o,delimiter='#')
for i in r:
print(i)
w.writerow(i)
s.close()
o.close()
def Retrive_csv():
s=open("Stu1.csv","r")
r=csv.reader(s)
print("\n")
for i in r:
print(i[0])
Store_csv()
Retrive_csv()

OUTPUT:

36
Stu.csv

Stu1.csv

37
Pgm:no 16
FORMATTING OUTPUT
1/09/2023

AIM:
Program to store and retrieve formatted sports’ performance(csv file).

CODING:
import csv
def Store_csv():
s=open("Sports.csv","w",newline='')
w=csv.writer(s)
n=int(input("Enter no.of sports going to enter:"))
for i in range(1,n+1):
s_na=input("Enter the Sports name of "+str(i))
c=input("Enter no.of competitions participated: ")
p=int(input("Enter the no.of prize won: "))
w.writerow([i,s_na,c,p])
s.close()
def Retrive_csv():
s=open("Sports.csv","r")
r=csv.reader(s)
print("="*50)
print("|{:^5} {:^15} {:^13} {:^11} |".format("SNo","Sport
Name","Competitions","Prizes won"))
print("="*50)
for i in r:

38
print("|{:^5} {:^15} {:^13} {:^11}
|".format(i[0],i[1],i[2],i[3]))
print("="*50)

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

39
OUTPUT:

Sports.csv

40
Pgm:no 17
PUSH AND POP OPERATIONS IN STACK
7/09/2023

AIM:
Program to Push and Pop items in stack.

CODING:
book=[]
def AddBook(bookname,book):
book.append(bookname)
print("Book is added")
def RemoveBook(book):
if len(book)==0:
print("Under Flow")
else:
s=book.pop()
print("Removed Book",s,"Successfully")
while True:
print("\n")
print("1)Add Book")
print("2)Remove Book")
print("3)Exit")

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

if choice == 1:

41
bo=input("Enter the bookname: ")
AddBook(bo,book)
elif choice == 2:
RemoveBook(book)
elif choice == 3:
break
else:
print("Invalid Input")

42
OUTPUT:

43
Pgm:no 18
PEEK AND DISPLAY OPERATIONS IN
20/09/2023 STACKS

AIM:
Program to Peek and Display items in stack.

CODING:
stack=[]
top=None
def Push(ele,stack):
global top
if len(stack)==0:
stack.append(ele)
top=0
print("Book Added")
else:
stack.append(ele)
top+=1
print("Book Added")
def Display(stack):
if len(stack)==0:
print("Empty Stack")
else:
print(stack[top],"<-top")
for i in stack[top-1::-1]:
print(i)

44
def Peek(stack,top):
if len(stack)==0:
print("UnderFlow")
else:
print("Peek value: ",stack[top])
while True:
print("\n")
print("1)Push Elements")
print("2)Display Elements")
print("3)Display the Peek value")
print("4)Exit")

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

if choice == 1:
bokid=int(input("Enter the Book No: "))
b=input("Enter the Book Name: ")
bo=[bokid,b]
Push(bo,stack)
elif choice == 2:
Display(stack)
elif choice == 3:
Peek(stack,top)
elif choice == 4:
break
else:
print("Invalid Input)

45
OUTPUT:

Pgm:no 19
46
STACK IMPLEMENTATION

3/10/2023

AIM:
Program to implement a stack and its operations.

CODING:
def isEmpty(stack):
if len(stack)==0:
return True
else:
return False
def Push(ele,stack):
global top
if isEmpty(stack):
stack.append(ele)
top=0
else:
stack.append(ele)
top+=1
def Pop(stack):
global top
if isEmpty(stack):
print("UnderFlow")
elif len(stack)==1:
p=stack.pop()

47
top=None
print("Poped Book: ",p)
else:
p=stack.pop()
top-=1
print("Poped Book: ",p)
def Display(stack):
if isEmpty(stack):
print("Empty Stack")
else:
for i in stack[:0:-1]:
print(i,end='-')
print(stack[0])
def Peek(stack,top):
if isEmpty(stack):
print("Empty Stack")
else:
print("The peek value is: ",stack[top])
stack=[]
top=None
while True:
print()
print("1)Push Elements")
print("2)Pop Elements")
print("3)Display Elements")
print("4)Display the Peek value")
print("5)Exit")

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

if choice == 1:
ele=input("Enter the BookName: ")
Push(ele,stack)
elif choice == 2:
Pop(stack)
elif choice == 3:
Display(stack)
elif choice == 4:
Peek(stack,top)
elif choice == 5:
break
else:
print("Invalid Input")

49
OUTPUT:

50
SQL Commands

51
Pgm:no 20
SQL COMMANDS
6/11/2023

a) Create:
Command:
create table students(
Sno int,
AdNo int Primary Key,
Name char(20),
Gender char(1),
DOB date,
Percentage float);

52
b)Alter:

c)Update:

53
d)Order By:

e)Delete:

54
f)Group By:

g)Joins:

55
Python Database Connectivity

56
Pgm:no 21
CONNECTIVITY-1
2/11/2023

AIM:
Program to display data of a table from sql database in python.

CODING:
import mysql.connector as sql
b=sql.connect(host="localhost",user="root",passwd="root",database=
'stu')
c=b.cursor()
c.execute("Select * from student")
o=c.fetchall()
for i in o:
print(i)
print("Total no.of records:",c.rowcount)
b.close()

57
OUTPUT:
SQL OUTPUT:

PYTHON OUTPUT:

58
Pgm:no 22
CONNECTIVITY-2
6/11/2023

AIM:
Program to display data of a table from sql database with rowcount in
python.

CODING:
import mysql.connector as sql
b=sql.connect(host="localhost",user="root",passwd="abhi",database=
"Employees")
c=b.cursor()
c.execute("Select * from emp")
for i in range(3):
o=c.fetchone()
print("Record {0}: {1}".format(c.rowcount,o))
b.close()

59
OUTPUT:
SQL OUTPUT:

PYTHON OUTPUT:

Pgm:no 23
60
CONNECTIVITY-3

8/11/2023

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

CODING:
import mysql.connector as a
s = a.connect(host="localhost", user="root",
passwd='abhi',database='Employees')

if s.is_connected():
cur=s.cursor()
opt='y'
while opt=='y':
No=int(input("enter emp no"))
Name=input("enter emp name")
department=input("enter emp department")
sal=int(input("enter sal"))
q="insert into emp values({},'{}','{}',
{})".format(No,Name,department,sal)
cur.execute(q)
s.commit()
print("rec stored")
opt=input("do you want to add another det(y/n)")

61
q="select * from emp";
cur.execute(q)
data=cur.fetchall()
for i in data:
print(i)
s.close()

62
OUTPUT:
SQL Table:
Before:

After:

PYTHON OUTPUT:

63
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='abhi',database='st
u')
c = b.cursor()
update_cmd = "update emp set salary = 400000 where deprtment =
'CEO'"
delete_cmd = "delete from emp where deprtment='Analyst'"

c.execute(update_cmd)
b.commit()

c.execute(delete_cmd)
b.commit()

64
OUTPUT:
SQL Table:
Before:

After:

65

You might also like