0% found this document useful (0 votes)
1 views51 pages

Python

The document is a practical file for Python programming submitted by a student at Guru Jambheshwar University. It includes a detailed index of various programming tasks, such as calculating factorials, checking for prime numbers, file operations, and implementing data structures like stacks and queues. Each program is accompanied by its aim, code, and expected output.

Uploaded by

codinghacking3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views51 pages

Python

The document is a practical file for Python programming submitted by a student at Guru Jambheshwar University. It includes a detailed index of various programming tasks, such as calculating factorials, checking for prime numbers, file operations, and implementing data structures like stacks and queues. Each program is accompanied by its aim, code, and expected output.

Uploaded by

codinghacking3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Practical File

of
Python Programming

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

GURU JAMBHESHWAR UNIVERSITY OF


SCIENCE AND TECHNOLOGY

Hisar - Haryana(India)

Submitted To : Submitted By:


Dr.Pawan Kumar Name - Hardik
Assistant Professor Roll No.: 210010140012
Department of CSE Branch: B.Tech(IT)
INDEX
Sr. Name of Practical Pg. Signature
No No.
1 Input any number from user and calculate factorial of a number 1
2 Input any number from user and check it is Prime no. or not 3
3 Write a program to find sum of elements of List recursively 5
4 Write a program to calculate the nth term of Fibonacci series 7
5 Program to search any word in given string/sentence 9
Program to read and display file content line by line with each word 11
6
separated by “#”
Program to read the content of file and display the total number of 13
7
consonants, uppercase, vowels and lower case characters
Program to create binary file to store Rollno and Name, Search any Rollno 15
8
and display name if Rollno found otherwise “Rollno not found”
Program to create binary file to store Rollno,Name and Marks and update 17
9
marks of entered Rollno
Program to read the content of file line by line and write it to another file 19
10
except for the lines contains “a” letter in it.
Program to create CSV file and store empno,name,salary and search any 21
11
empno and display name,salary and if not found appropriate message.
12 Program to generate random number 1-6, simulating a dice 23
13 Program to implement Stack in Python using List 25
14 Program to implement Queue in Python using List 28
15 Program to perform operations on a List 31
16 Program to perform operations on a Dictionary 33
17 Two assignment on sets to perform operation union, intersection, differentiate 35
Program to take 10 sample phishing email, and find the most common 37
18
word occurring
19 Program to create 21 Stick Game so that computer always wins 39
Program to connect with database and store record of employee and 42
20
display records.
Program to connect with database and search employee number in table 44
21 employee and display record, if empno not found display appropriate
message.
Program to connect with database and update the employee record of 46
22
entered empno.
Program to connect with database and delete the record of entered 48
23
employee number.
Program-1

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

Aim :Write a program to find sum of elements of List recursively

Program:
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)

5
Output:

6
Program-4

Aim : Write a program to calculate the nth term of Fibonacci series

Program:
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)

7
Output:

8
Program-5

Aim : Program to search any word in given string/sentence

Program:
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")

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()

NOTE : if the original content of file is:


India is my country
My name is Mohit Kumar
Today is my Python Practical

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()

NOTE : if the original content of file is:


India is my country
My name is &$Mohit Kumar
Today is my Python Practical@%

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")

for line in f1:


if 'a' not in line:
f2.write(line)

print("File Copied Successfully!")


f1.close()
f2.close()

NOTE : if the original content of file is:


India is my country
My name is &$Tanishk
Today is my Python Practical@%

19
Output:

NOTE : After copy content of the file:


India is my country
My name is &$Tanishk
Today is my Python Practical@%

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

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)")

21
Output:

22
Program-12

Aim :Program to generate random number 1-6, simulating a dice

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

Aim : Program to implement Stack in Python using List

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()

# main begins here


S=[]
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

26
Output:

27
Program-14

Aim : Program to implement Queue in Python using List

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

Aim : Program to perform operations on list.

Program:
# declaring a list of integers
iList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# List slicing operations


# printing the complete list
print('iList: ',iList)
# printing first element
print('first element: ',iList[0])
# printing fourth element
print('fourth element: ',iList[3])
# printing list elements from 0th index to 4th index
print('iList elements from 0 to 4 index:',iList[0: 5])
# printing list -7th or 3rd element from the list
print('3rd or -7th element:',iList[-7])

# appending an element to the list


iList.append(111)
print('iList after append():',iList)

# finding index of a specified element


print('index of \'80\': ',iList.index(80))

# sorting the elements of iLIst


iList.sort()
print('after sorting: ', iList);

# popping an element
print('Popped elements is: ',iList.pop())
print('after pop(): ', iList);

# removing specified element


iList.remove(80)
31
print('after removing \'80\': ',iList)

# inserting an element at specified index


# inserting 100 at 2nd index
iList.insert(2, 100)
print('after insert: ', iList)

# counting occurances of a specified element


print('number of occurences of \'100\': ', iList.count(100))

# extending elements i.e. inserting a list to the list


iList.extend([11, 22, 33])
print('after extending:', iList)

#reversing the list


iList.reverse()
print('after reversing:', iList)

Output:

32
Program-16

Aim : Program to perform operations on a dictionary.

Program:
my_dict = {'Name': 'Mohit', 'Age': '21', 'Country': 'India'}
my_dict.clear()
print(my_dict)

d = {'Name': 'Mohit Kumar', 'Age': '21', 'Country': 'India'}


print(d.get('Name'))
print(d.get('Gender'))

print(list(d.items())[1][0])
print(list(d.items())[1][1])

print(list(d.keys()))
print(list(d.values()))

d2 = {'Name': 'Saurabh', 'Age': '20'}

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

Aim : Program to create 21 Stick Game so that computer always wins

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])

ans = input("SEARCH MORE (Y) :")

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy