0% found this document useful (0 votes)
5 views17 pages

Python Programs for Factorial, Prime, and More

The document contains multiple programming experiments demonstrating various functionalities such as calculating factorials, checking for prime numbers, summing list elements recursively, generating Fibonacci series, searching for words in strings, and managing employee records in a database. Each experiment includes code snippets, user inputs, and outputs showcasing the results of the programs. The document serves as a practical guide for implementing basic programming concepts in Python.

Uploaded by

itzmeajayc
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)
5 views17 pages

Python Programs for Factorial, Prime, and More

The document contains multiple programming experiments demonstrating various functionalities such as calculating factorials, checking for prime numbers, summing list elements recursively, generating Fibonacci series, searching for words in strings, and managing employee records in a database. Each experiment includes code snippets, user inputs, and outputs showcasing the results of the programs. The document serves as a practical guide for implementing basic programming concepts in Python.

Uploaded by

itzmeajayc
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

Date : Experiment No: 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

Page : 1
Date : Experiment No:2

Program 1: 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([Link](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 ##

Page : 2
Date : Experiment No: 3

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

#Program to find sum of elements of list recursively


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)+":"))
[Link](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

Page : 3
Date : Experiment No: 4

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

#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

Page : 4
Date : Experiment No: 5

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

#Program to find the occurence of any word in a string


def countWord(str1,word):
s = [Link]()
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
Date : Experiment No: 11

Program 1: Program to create CSV file and store empno,name,salary and


search any empno and display name,salary and if not found appropriate
message.

import csv
with open('[Link]',mode='a') as csvfile:
mywriter = [Link](csvfile,delimiter=',')
ans='y'
while [Link]()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
[Link]([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('[Link]',mode='r') as csvfile:
myreader = [Link](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)")

Page : 13
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

Page : 14
Date : Experiment No: 15

Program 1: Program to take 10 sample phishing email, and find the most
common word occurring

#Program to take 10 sample phishing mail


#and count the most commonly occuring word
phishingemail=[
"jackpotwin@[Link]",
"claimtheprize@[Link]",
"youarethewinner@[Link]",
"luckywinner@[Link]",
"spinthewheel@[Link]",
"dealwinner@[Link]"
"luckywinner@[Link]"
"luckyjackpot@[Link]"
"claimtheprize@[Link]"
"youarelucky@[Link]"
]
myd={}
for e in phishingemail:
x=[Link]('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=[Link])
print("Most Common Occuring word is :",key_max)

OUTPUT

Most Common Occuring word is : [Link]

Page : 23
Date : Experiment No: 16

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

Rule of Game (Total Sticks = 21):


1) User and Computer both can pick stick one by one
2) Maximum stick both can pick is 4 i.e. 1 to 4
3) Anyone with last stick will be the looser

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
PrintStick(TotalStick)
if TotalStick==1:
print("## WINNER : COMPUTER ##")
win=True
print("*"*60)
input("Press any key...")
humanPlayer=True
Page : 24
OUTPUT

==== Welcome To Stick Picking Game :: Computer Vs User =====


Rule: 1) Both User and Computer can pick sticks between 1 to 4 at a time
2) Whosoever picks the last stick will be the looser
==== Lets Begin ======
Enter Your Name :RAJ
ooooooooooooooooooooo
|||||||||||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick3
oooooooooooooooooo
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
************************************************************
Press any key...
Computer Picks : 2 Sticks
oooooooooooooooo
||||||||||||||||
||||||||||||||||
||||||||||||||||
||||||||||||||||
************************************************************
Press any key...
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick4
oooooooooooo
||||||||||||
||||||||||||
||||||||||||
||||||||||||
************************************************************
Press any key...
Computer Picks : 1 Sticks
ooooooooooo
|||||||||||
|||||||||||
|||||||||||
|||||||||||
************************************************************
Press any key...
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick2
ooooooooo
|||||||||
|||||||||
|||||||||
|||||||||
Page : 25
************************************************************
Press any key...
Computer Picks : 3 Sticks
oooooo
||||||
||||||
||||||
||||||
************************************************************
Press any key...
You Can Pick stick between 1 to 4
RAJ: Enter Number of Stick to Pick3
ooo
|||
|||
|||
|||
************************************************************
Press any key...
Computer Picks : 2 Sticks
o
|
|
|
|
## WINNER : COMPUTER ##
************************************************************
Press any key...

Page : 26
Date : Experiment No: 17

Program 1: Program to connect with database and store record of employee


and display records.

import [Link] as mycon


con = [Link](host='[Link]',user='root',password="admin")
cur = [Link]()
[Link]("create database if not exists company")
[Link]("use company")
[Link]("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
[Link]()
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)
[Link](query)
[Link]()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
[Link](query)
result = [Link]()
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:
[Link]()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")

Page : 27
OUTPUT

1. ADD RECORD
2. 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!! ##

Page : 28
Date : Experiment No: 18

Program 1: Program to connect with database and search employee number


in table employee and display record, if empno not found display
appropriate message.

import [Link] as mycon


con = [Link](host='[Link]',user='root',password="admin",
database="company")
cur = [Link]()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while [Link]()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
[Link](query)
result = [Link]()
if [Link]==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 80000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :4
Sorry! Empno not found
SEARCH MORE (Y) :n

Page : 29
Date : Experiment No: 19

Program 1: Program to connect with database and update the employee


record of entered empno.

import [Link] as mycon


con = [Link](host='[Link]',user='root',password="admin",
database="company")
cur = [Link]()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'
while [Link]()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
[Link](query)
result = [Link]()
if [Link]==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 [Link]()=='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)
[Link](query)
[Link]()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")

Page : 30
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 WANT TO CHANGE )SALES
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 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

Page : 31
Date : Experiment No: 20

Program 1: Program to connect with database and delete the record of


entered employee number.

import [Link] as mycon


con = [Link](host='[Link]',user='root',password="admin",
database="company")
cur = [Link]()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while [Link]()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
[Link](query)
result = [Link]()
if [Link]==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 [Link]()=='y':
query="delete from employee where empno={}".format(eno)
[Link](query)
[Link]()
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

Page : 32

[Link]

You might also like