0% found this document useful (0 votes)
306 views15 pages

12th CS Practical Manual-1

The document provides 15 programming problems and their solutions, including programs to calculate factorial, check if a number is prime, search words in a string, perform stack operations, find most common words in phishing emails, and calculate loan EMI using NumPy. The programs cover a range of tasks like file handling, searching/sorting, mathematical calculations, and data structures. Sample inputs, outputs and source code are provided for each programming problem and solution.

Uploaded by

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

12th CS Practical Manual-1

The document provides 15 programming problems and their solutions, including programs to calculate factorial, check if a number is prime, search words in a string, perform stack operations, find most common words in phishing emails, and calculate loan EMI using NumPy. The programs cover a range of tasks like file handling, searching/sorting, mathematical calculations, and data structures. Sample inputs, outputs and source code are provided for each programming problem and solution.

Uploaded by

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

Program 1:

Write a Program to find factorial of the entered number.

Aim: To write a program to calculate factorial of entered number.

Algorithm:
Step 1: Start a program
Step 2: Declare variable num, fact, i
Step 3: Use a while loop to multiply the number to the factorial variable and then increment
the number.
Step 4: Repeat until i<=num
4.1 fact=fact*i
4.2 i=i+1
Step 5: Print the factorial of the number
Step 6 : Exit

Source Code:

Output:

Result :
Thus the above program is executed and output is verified successfully.

Program 2: Write a Program to enter the number of terms and to print the Fibonacci Series.
Output:

Program 3: 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 ##
Page :

Program 4: Read a text file and display the number of


vowels/consonants/uppercase/lowercase characters in the file
Output:

Program :5 Read a text file line by line and display


each word separated by a '#' in Python

filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()

output:

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


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:

================= RESTART: C:/Python27/cs practical file.csv


=================

Enter any sentence :'my computer your computer our computer everyones
computer'

Enter word to search in sentence :'computer'

('## ', 'computer', ' occurs ', 4, ' times ## ')

>>>

================= RESTART: C:/Python27/cs practical file.csv


=================

Enter any sentence :'learning python is fun'


Enter word to search in sentence :'java'

('## Sorry! ', 'java', ' not present ')

>>>

Program :7 Create a binary file with name and roll number of the students.
Search for a given roll number and display the name of student.

Output:
Program : 8Write a program to calculate compound
interest.

Source Code:

p=float(input("Enter the principal amount : "))


r=float(input("Enter the rate of interest : "))
t=float(input("Enter the time in years : "))
x=(1+r/100)**t
CI= p*x-p
print("Compound interest is : ", round(CI,2))

Output:

Enter the principal amount : 5000

Enter the rate of interest : 4

Enter the time in years : 2

('Compound interest is : ', 408.0)

>>>

Program : 9 Write a program to display ASCII code of a character and


vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to
find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:

var=False

Output:

Press-1 to find the ordinal value of a character


Press-2 to find a character of a value
1
Enter a character : a
97
Do you want to continue? Y/N
Y
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
2
Enter an integer value: 65
A
Do you want to continue? Y/N

Program : 10 Write a menu based program to perform the operation on


stack in python.

class Stack:
def __init__(self):
self.items = [ ]

def isEmpty(self): # Checks whether the stack is empty or not


return self.items == [ ]

def push(self, item): #Insert an element


self.items.append(item)

def pop(self): # Delete an element


return self.items.pop( )

def peek(self): #Check the value of top


return self.items[len(self.items)-1]

def size(self): # Size of the stack i.e. total no. of elements in stack
return len(self.items)

s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")
choice=int(input("Enter your choice (1-5) : "))
if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You enetered wrong choice ")
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False

Output:
MENU BASED STACK
1. Push
2. Pop
3. Display
4. Size of Stack
5. Value at Top
Enter your choice (1-5) : 1
Enter the element: 45
Do you want to continue? Y/N
y
1. Push
2. Pop
3. Display
4. Size of Stack
5. Value at Top
Enter your choice (1-5) : 3
['45']
Do you want to continue? Y/N
y
1. Push
2. Pop
3. Display
4. Size of Stack
5. Value at Top

Program 11: 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=[
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
]
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)
OUTPUT
Most Common Occuring word is : mymoney.com

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

OUTPUT:
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- A list Num contains the following elements: 3, 21, 5, 6, 14, 8, 14, 3 WAP to swap the
content with next value divisible by 7 so that the resultant array will look like: 3, 5, 21, 6, 8, 14, 3, 14
OUTPUT:

Program:14 : Write a program to calculate EMI for a loan using numpy.

Source Code:

import numpy as np

interest_rate= float(input("Enter the interest rate : "))

monthly_rate = (interest_rate)/ (12*100)

years= float(input("Enter the total years : "))

number_month = years * 12

loan_amount= float(input("Enter the loan amount : "))

emi = abs(np.pmt(monthly_rate, number_month, loan_amount))

print("Your EMI will be Rs. ", round(emi, 2))


OUTPUT:

Enter the interest rate : 7.5

Enter the total years : 15

Enter the loan amount : 200000

Your EMI will be Rs. 1854.02

PROGRAM:15: Write a program to perform read and write operation with .csv file.

SOURCE CODE:

import csv

def readcsv():

with open('C:\\Users\\ViNi\\Downloads\\data.csv','rt')as f:

data = csv.reader(f) #reader function to generate a reader object

for row in data:

print(row)

def writecsv( ):

with open('C:\\Users\\ViNi\\Downloads\\data.csv', mode='a', newline='') as file:

writer = csv.writer(file, delimiter=',', quotechar='"')

#write new record in file

writer.writerow(['4', 'Devansh', 'Arts', '404'])

print("Press-1 to Read Data and Press-2 to Write data: ")

a=int(input())

if a==1:

readcsv()

elif a==2:

writecsv()

else:

print("Invalid value")

OUTPUT:
Press-1 to Read Data and Press-2 to Write data:

['Roll No.', 'Name of student', 'stream', 'Marks']

['1', 'Anil', 'Arts', '426']

['2', 'Sujata', 'Science', '412']

['3', 'Shivani', 'Commerce', '448']

['4', 'Devansh', 'Arts', '404']

You might also like