Python
Python
of
Python Programming
Hisar - Haryana(India)
Aim : Input any number from the user and calculate factorial of a number
Program:
num = int(input("Enter any number :"))
fact = 1
n = num
# storing num in n for printing while num>1:
while num>1:
fact = fact * num
num-=1
print("Factorial of ", n , " is :",fact)
1
Output:
2
Program-2
Aim : Input any number from user and check it is Prime no. or not
Program:
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")
3
Output:
4
Program-3
Program:
def findSum(lst,num):
if num==0:
return 0
else:
return lst[num-1]+findSum(lst,num-1)
sum = findSum(mylist,len(mylist))
print("Sum of List items ",mylist, " is :",sum)
5
Output:
6
Program-4
Program:
def nthfiboterm(n):
if n<=1:
return n
else:
return (nthfiboterm(n-1)+nthfiboterm(n-2))
7
Output:
8
Program-5
Program:
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
9
Output:
10
Program-6
Aim : Program to read and display file content line by line with each word separated by
“#”
Program:
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
11
Output:
12
Program-7
Aim : Program to read the content of file and display the total number of consonants,
uppercase, vowels and lower case characters
Program:
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()
13
Output:
14
Program-8
Aim : Program to create binary file to store Rollno and Name, Search any Rollno and
display name if Rollno found otherwise “Rollno not found”
Program:
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()
15
Output:
16
Program-9
Aim : Program to create binary file to store Rollno,Name and Marks and update marks
of entered Rollno
Program:
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
17
Break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
Output:
18
Program-10
Aim :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:
f1 = open("file1.txt")
f2 = open("file1copy.txt","w")
19
Output:
20
Program-11
Aim : Program to create CSV file and store empno,name,salary and search any empno
and display name,salary and if not found appropriate message.
Program:
import csv
21
Output:
22
Program-12
Program:
import random
while True:
print("="*55)
print("********************ROLLING THE DICE************")
print("="*55)
num = random.randint(1,6)
if num == 6:
print("Hey.... You got",num,'....Congratulations!!!!')
elif num == 1:
print("well tried....But you got ",num)
else:
print("You got: ",num)
ch = input("Roll again ? (Y/N)")
if ch in "Nn":
break
print("Thanks for Playing !!!!!!!!!!")
23
Output:
24
Program-13
Program:
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:
25
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
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
26
Output:
27
Program-14
Program:
def isEmpty(Q):
if len(Q)==0:
return True
else:
return False
def Enqueue(Q,item):
Q.append(item)
if len(Q)==1:
front=rear=0
else:
rear=len(Q)-1
def Dequeue(Q):
if isEmpty(Q):
return "Underflow"
else:
val = Q.pop(0)
if len(Q)==0:
front=rear=None
return val
def Peek(Q):
if isEmpty(Q):
return "Underflow"
else:
front=0
return Q[front]
def Show(Q):
if isEmpty(Q):
print("Sorry No items in Queue ")
else:
t = len(Q)-1
28
print("(Front)",end=' ')
front = 0
i=front
rear = len(Q)-1
while(i<=rear):
print(Q[i],"==>",end=' ')
i+=1
print()
Q=[] #Queue
front=rear=None
print("**** QUEUE DEMONSTRATION ******")
print("1. ENQUEUE ")
print("2. DEQUEUE")
print("3. PEEK")
print("4. SHOW QUEUE ")
print("0. EXIT")
while True:
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Insert :"))
Enqueue(Q,val)
elif ch==2:
val = Dequeue(Q)
if val=="Underflow":
print("Queue is Empty")
else:
print("\nDeleted Item was :", val)
elif ch==3:
val = Peek(Q)
if val=="Underflow":
print("Queue Empty")
else:
print("Front Item :", val)
elif ch==4:
Show(Q)
elif ch==0:
print("Bye")
break
29
Output:
30
Program-15
Program:
# declaring a list of integers
iList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# popping an element
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);
Output:
32
Program-16
Program:
my_dict = {'Name': 'Mohit', 'Age': '21', 'Country': 'India'}
my_dict.clear()
print(my_dict)
print(list(d.items())[1][0])
print(list(d.items())[1][1])
print(list(d.keys()))
print(list(d.values()))
d.update(d2)
print(d)
d.pop('Age')
print(d)
d.popitem()
print(d)
33
Output:
34
Program-17
Aim : Program to take 10 sample phishing email, and find the most common word
occurring
Program:
def perform_set_operations(set_A, set_B):
# Union
union_result = set_A.union(set_B)
# Intersection
intersection_result = set_A.intersection(set_B)
# Difference (A - B)
difference_A_B = set_A.difference(set_B)
# Difference (B - A)
difference_B_A = set_B.difference(set_A)
# Print results
print("Union of sets A and B:", union_result)
print("Intersection of sets A and B:", intersection_result)
print("Difference (A - B):", difference_A_B)
print("Difference (B - A):", difference_B_A)
# Main function
def main():
# Sample sets
set_A = {10, 20, 30, 40, 50}
set_B = {40, 50, 60, 70, 80}
# Perform set operations
perform_set_operations(set_A, set_B)
if __name__ == "__main__":
main()
35
Output:
36
Program-18
Aim : Program to take 10 sample phishing email, and find the most common word
occurring
Program:
phishingemail=[
"jackpotwin@gmail.com",
"claimtheprize@gmail.com",
"youarethewinner@lottery.com",
"luckywinner@mymoney.com",
"spinthewheel@flipkart.com",
"dealwinner@snapdeal.com",
"luckywinner@gamil.com",
"luckyjackpot@americanlottery.com",
"claimtheprize@gmail.com",
"youarelucky@mymoney.com"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
37
Output:
38
Program-19
Program:
def PrintStick(n):
print("o "*n)
print("| "*n)
print("| "*n)
print("| "*n)
print("| "*n)
TotalStick=21
win=False
humanPlayer=True
print("==== Welcome To Stick Picking Game :: Computer Vs User =====")
print("Rule: 1) Both User and Computer can pick sticks between 1 to 4 at a time")
print(" 2) Whosoever picks the last stick will be the looser")
print("==== Lets Begin ======")
playerName = input("Enter Your Name :")
userPick=0
PrintStick(TotalStick)
while win==False:
if humanPlayer==True:
print("You Can Pick stick between 1 to 4")
userPick=0
while userPick<=0 or userPick>4:
userPick = int(input(playerName +": Enter Number of Stick to
Pick"))
TotalStick= TotalStick - userPick
humanPlayer=False
PrintStick(TotalStick)
print("*"*60)
input("Press any key...")
else:
computerPick = (5-userPick)
print("Computer Picks : ",computerPick," Sticks ")
TotalStick=TotalStick -computerPick
39
PrintStick(TotalStick)
if TotalStick==1:
print("## WINNER : COMPUTER ##")
win=True
print("*"*60)
input("Press any key...")
humanPlayer=True
Output:
40
41
Program-20
Aim : Program to connect with database and store record of employee and display
records.
Program:
import mysql.connector as myConn
mydb = myConn.connect(host='localhost',user='root',passwd='KaranSql@021102')
db_cursor = mydb.cursor()
# db_cursor.execute("Create database Company")
# db_cursor.execute("show databases")
db_cursor.execute("use Company")
# db_cursor.execute("create table employee(empno int,name varchar(20),dept
varchar(20),salary int)")
# mydb.commit()
db_cursor.execute("show tables")
for i in db_cursor:
print(i)
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)
db_cursor.execute(query)
mydb.commit()
print("## Data Saved ##")
elif choice == 2:
query = "select * from employee"
db_cursor.execute(query)
result = db_cursor.fetchall()
print("%10s" % "EMPNO", "%20s" % "NAME", "%15s" %
42
"DEPARTMENT", "%10s" % "SALARY")
for row in result:
print("%10s" % row[0], "%20s" % row[1], "%15s" % row[2], "%10s" %
row[3])
elif choice == 0:
mydb.close()
print("## Bye!! ##")
else:
print("Invalid Choice")
Output:
43
Program-21
Aim : Program to connect with database and search employee number in table employee
and display record, if empno not found display appropriate message.
Program:
import mysql.connector as myConn
mydb = myConn.connect(host='localhost',user='root',passwd='KaranSql@021102')
db_cursor = mydb.cursor()
db_cursor.execute("use Company")
print("EMPLOYEE SEARCHING FORM")
print("\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query = "select * from employee where empno={}".format(eno)
db_cursor.execute(query)
result = db_cursor.fetchall()
if db_cursor.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])
44
Output:
45
Program-22
Aim : Program to connect with database and update the employee record of entered
empno.
Program:
import mysql.connector as myConn
mydb = myConn.connect(host='localhost',user='root',passwd='KaranSql@021102')
db_cursor = mydb.cursor()
db_cursor.execute("use Company")
print("EMPLOYEE UPDATION FORM")
print("\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
db_cursor.execute(query)
result = db_cursor.fetchall()
if db_cursor.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,
46
eno)
db_cursor.execute(query)
mydb.commit()
print("## RECORD UPDATED ## ")
ans = input("UPDATE MORE (Y) :")
Output:
47
Program-23
Aim : Program to connect with database and delete the record of entered employee
number.
Program:
import mysql.connector as myConn
mydb = myConn.connect(host='localhost',user='root',passwd='KaranSql@021102')
db_cursor = mydb.cursor()
db_cursor.execute("use Company")
print("EMPLOYEE DELETION FORM")
print("\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
db_cursor.execute(query)
result = db_cursor.fetchall()
if db_cursor.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)
db_cursor.execute(query)
mydb.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
48
Output:
49