Program-1
Program 1: Input any number from user and calculate factorial of a number
# Program to calculate factorial of entered number
num = int(input("Enter any number :"))
fact = 1
n = num # storing num in n for printing
while num>1: # loop to iterate from n to 2
fact = fact * num
num-=1
print("Factorial of ", n , " is :",fact)
OUTPUT
Enter any number :6
Factorial of 6 is : 720
Program 2
Program 2 : Input any number from user and check it is Prime no. or not
#Program to input any number from user
#Check it is Prime number of not
import math
num = int(input("Enter any number :"))
isPrime=True
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
isPrime=False
if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")
OUTPUT
Enter any number :117
## Number is not Prime ##
>>>
Enter any number :119
## Number is not Prime ##
>>>
Enter any number :113
## Number is Prime ##
>>>
Enter any number :7
## Number is Prime ##
>>>
Enter any number :19
## Number is Prime ##
Program 3
Program 3 : Write a program to find sum of elements of List recursively
#Program to find sum of elements of list
def findSum(lst,num):
if num==0:
return 0
else:
return lst[num-1]+findSum(lst,num-1)
mylist = [] # Empty List
#Loop to input in list
num = int(input("Enter how many number :"))
for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylist.append(n) #Adding number to list
sum = findSum(mylist,len(mylist))
print("Sum of List items ",mylist, " is :",sum)
OUTPUT
Enter how many number :6
Enter Element 1:10
Enter Element 2:20
Enter Element 3:30
Enter Element 4:40
Enter Element 5:50
Enter Element 6:60
Sum of List items [10, 20, 30, 40, 50, 60] is : 210
Program 4
Program 4: Write a program to calculate the nth term of Fibonacci seriesusing
userdefined function
#Program to find 'n'th term of fibonacci series
#Fibonacci series : 0,1,1,2,3,5,8,13,21,34,55,89,...
#nth term will be counted from 1 not 0
def nthfiboterm(n):
if n<=1:
return n
else:
return (nthfiboterm(n-1)+nthfiboterm(n-2))
num = int(input("Enter the 'n' term to find in fibonacci :"))
term =nthfiboterm(num)
print(num,"th term of fibonacci series is :",term)
OUTPUT
Enter the 'n' term to find in fibonacci :10
10 th term of fibonacci series is : 55
Program 4
Program 5 : Program to search any word in given string/sentence using user
defined functions
#Program to find the occurence of any word in a string
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")
else:
print("## ",word," occurs ",count," times ## ")
OUTPUT
Enter any sentence :my computer your computer our computer everyones computer
Enter word to search in sentence :computer
## computer occurs 4 times ##
Enter any sentence :learning python is fun
Enter word to search in sentence :java
## Sorry! java not present
Page : 5
Program 6
Program 6 : Program to read and display file content line by line with each
word separated by „#‟
#Program to read content of file line by line
#and display each word separated by '#'
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
NOTE : if the original content of file is:
India is my country
I love python
Python learning is fun
OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#
Program 7
Program 7 : Program to read the content of file and display the total number
of consonants, uppercase, vowels and lower case characters‟
#Program to read content of file
#and display total number of vowels, consonants, lowercase and uppercase characters
f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
NOTE : if the original content of file is:
India is my country
I love python
Python learning is fun
123@
OUTPUT
Total Vowels in file : 16
Total Consonants in file n : 30
Total Capital letters in file :2
Total Small letters in file : 44
Total Other than letters :4
Program 8
Program 8: Program to create binary file to store Rollno and Name, Search
any Rollno and display name if Rollno found otherwise “Rollno not found”
#Program to create a binary file to store Rollno and name
#Search for Rollno and display record if found
#otherwise "Roll no. not found"
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Add More ?(Y)y
Enter Roll Number :2
Enter Name :Jasbir
Add More ?(Y)y
Enter Roll Number :3
Enter Name :Vikral
Add More ?(Y)n
Enter Roll number to search :2
## Name is : Jasbir ##
Search more ?(Y) :y
Enter Roll number to search :1
## Name is : Amit ##
Search more ?(Y) :y
Enter Roll number to search :4
####Sorry! Roll number not found ####
Search more ?(Y) :n
Program 9 Experiment No: 9
Program 9: Program to create binary file to store Rollno,Name and Marks
and update marks of entered Rollno
#Program to create a binary file to store Rollno and name
#Search for Rollno and display record if found
#otherwise "Roll no. not found"
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Enter Marks :99
Add More ?(Y)y
Enter Roll Number :2
Enter Name :Vikrant
Enter Marks :88
Add More ?(Y)y
Enter Roll Number :3
Enter Name :Nitin
Enter Marks :66
Add More ?(Y)n
Enter Roll number to update :2
## Name is : Vikrant ##
## Current Marks is : 88 ##
Enter new marks :90
## Record Updated ##
Update more ?(Y) :y
Enter Roll number to update :2
## Name is : Vikrant ##
## Current Marks is : 90 ##
Enter new marks :95
## Record Updated ##
Update more ?(Y) :n
Program 10
Program 10: Program to read the content of file line by line and write it to
another file except for the lines contains „a‟ letter in it.
#Program to read line from file and write it to another line
#Except for those line which contains letter 'a'
f1 = open("file2.txt")
f2 = open("file2copy.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print(“## File Copied Successfully! ##”)
f1.close()
f2.close()
NOTE: Content of file2.txt
a quick brown fox
one two three four
five six seven
India is my country
eight nine ten
bye!
OUTPUT
## File Copied Successfully! ##
NOTE: After copy content of file2copy.txt
one two three four
five six seven
eight nine ten
bye!
Program11
Program 11: Program to create CSV file and store empno,name,salary
and search any empno and display name,salary and if not found
appropriatemessage.
import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")
Enter Employee Number 1
Enter Employee Name Amit
Enter Employee Salary :90000
## Data Saved... ##
Add More ?y
Enter Employee Number 2
Enter Employee Name Sunil
Enter Employee Salary :80000
## Data Saved... ##
Add More ?y
Enter Employee Number 3
Enter Employee Name Satya
Enter Employee Salary :75000
## Data Saved... ##
Add More ?n
Enter Employee Number to search :2
============================
NAME : Sunil
SALARY : 80000
Search More ? (Y)y
Enter Employee Number to search :3
============================
NAME : Satya
SALARY : 75000
Search More ? (Y)y
Enter Employee Number to search :4
==========================
EMPNO NOT FOUND
==========================
Search More ? (Y)n
Program 13
Program 1 3: Program to implement Stack in Python using List
def isEmpty(S):
if len(S)==0:
return True
else:
return False
def Push(S,item):
S.append(item)
top=len(S)-1
def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val
def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break
OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :10
Cont…
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :30
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 30 <== 20 <== 10 <==
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :3
Top Item : 30
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :2
Deleted Item was : 30
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 20 <== 10 <==
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :0
Bye
Program 14
Program 14: Program to connect with database and store record of employee
and display records.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
OUTPUT
0. ADD RECORD
1. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0
## Bye!! ##
Program 15
Program1 5 : Program to connect with database and search employee
number in table employee and display record, if empno not found display
appropriate message.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
OUTPUT
########################################
EMPLOYEE SEARCHING FORM
########################################
ENTER EMPNO TO SEARCH :1
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 580000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :4
Sorry! Empno not found
SEARCH MORE (Y) :n
Program16
Program 16: Program to connect with database and update the employee
record of entered empno.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT
TO CHANGE )")
if d=="":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT
WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where empno={}".format
(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
OUTPUT
########################################
EMPLOYEE UPDATION FORM
########################################
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000
## ARE YOUR SURE TO UPDATE ? (Y) :y
== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD UPDATED ##
UPDATE MORE (Y) :y
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000
## ARE YOUR SURE TO UPDATE ? (Y) :y
== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WAN
T TO CHANGE )SALESENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE
)
## RECORD UPDATED ##
UPDATE MORE (Y) :Y
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 90000
## ARE YOUR SURE TO UPDATE ? (Y) :Y
== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE ) 91000
## RECORD UPDATED ##
UPDATE MORE (Y) :Y
ENTER EMPNO TO UPDATE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000
## ARE YOUR SURE TO UPDATE ? (Y) :N
UPDATE MORE (Y) :N
Program 17
Program 17: Program to connect with database and delete the record of
entered employee number.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT
########################################
EMPLOYEE DELETION FORM
########################################
ENTER EMPNO TO DELETE :2
EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000
## ARE YOUR SURE TO DELETE ? (Y) :y
=== RECORD DELETED SUCCESSFULLY! ===
DELETE MORE ? (Y) :y
ENTER EMPNO TO DELETE :2
Sorry! Empno not found
DELETE MORE ? (Y) :n
#1. Create a student table with the student id, name, and marks as attributes
where the student id is the primary key.
#2. Insert the details of a new student in the above table.
#3. Delete the details of a particular student in the above table.
1|Page
#4. Use the select command to get the details of the students with marks
more than 80.
#5. Create a new table (order ID, customer Name, and order Date) by joining
two tables (order ID, customer ID, and order Date) and (customer ID, customer
2|Page
#6. Create a foreign key in one of the two tables mentioned above
#7. Find the min, max, sum, and average of the marks in a student marks table.
#8. Find the total number of customers from each country in the table
(customer ID, customer Name, country) using group by.
3|Page
#9. Create a new table (name, date of birth) by joining two tables (student id,
name) and (student id, date of birth).
#10. Write a SQL query to order the (student ID, marks) table in descending order
of the marks.
4|Page