0% found this document useful (0 votes)
12 views39 pages

Write a Python Program to Check the Given Number is Prime or Not

The document is a Python practical file submitted by a student, Aryan, detailing various Python programs. It includes programs for checking prime numbers, counting word occurrences, finding element frequencies in lists, and performing string manipulations, among others. Each section contains code snippets along with example outputs demonstrating the functionality of the programs.

Uploaded by

Aryan Sheoran
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views39 pages

Write a Python Program to Check the Given Number is Prime or Not

The document is a Python practical file submitted by a student, Aryan, detailing various Python programs. It includes programs for checking prime numbers, counting word occurrences, finding element frequencies in lists, and performing string manipulations, among others. Each section contains code snippets along with example outputs demonstrating the functionality of the programs.

Uploaded by

Aryan Sheoran
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 39

PM SHRI KENDRIYA

VIDYALAYA NO 1 AFS
GURUGRAM HARYANA

COM
PUTER SCIENCE
PRACTICAL FILE
SUBMITTED
BY : ARYAN
ROLL NO : 07
CLASS:12A
# WRITE A PYTHON PROGRAM
TO CHECK THE GIVEN
NUMBER IS PRIME OR
NOT

a=int(input("Enter a number : "))


half=a/2
i=2
ctr=0

print ("The factors of ",a,"are :")

while i<=half:
if a%i==0:
print ("It's Not a prime number")
break
i=i+1

if i>half:
print ("\nIt is a prime number")

Run Part :-

Enter a number : 7
The factors of 7 are :
It is a prime number
# WRITE A PYTHON PROGRAM TO
COUNT THE OCCURRENCES OF A
WORD (WHOLE WORD) IN A STRING
USING USER defined function.
def countword(string,s):
k=0
words = f.split()
print(f)
print(words)

for i in words:
if(i==s):
k=k+1
print("Occurrences of the word:")
print(k)

#__main__

f="this is is a book"
search ="is"
countword(f,search)

Run Part:-
this is is a book
['this', 'is', 'is', 'a', 'book']
Occurrences of the word:2
# Write a Python program to show the
frequency of each element in list.
'''
L1=[]
n=int(input("enter the number of elements ="))
for i in range(n):
item = int(input('Enter No. ='))
L1.append(item)
'''
L1=[11,2,2,1,3,11,4]
print("the elementsin List L1",L1)
L2=L1
L2.sort()
print("the elementsin List L2",L2)

d=dict()
for ch in L2:
if ch in d:
d[ch]+=1
else:
d[ch]=1

for i in d:
print (i, d[i])
Run Part :-
the elementsin List L1 [11, 2, 2, 1, 3, 11, 4]
the elementsin List L2 [1, 2, 2, 3, 4, 11, 11]
11
22
31
41
11 2
# Write a Python program to search
an element in a list and display the
frequency of element present in
list and their location.
'''
L1=[]
n=int(input("enter the number of elements ="))
for i in range(n):
item = int(input('Enter No. ='))
L1.append(item)
'''
L1=[3,11,2,2,1,3,11,3,3]
print("the elements in List L1",L1)
# searched element
x=3
#count the frequency of x
d=dict()
d[x]=0
for ch in L1:
if x==int(ch):
d[x]+=1
print("Frequency of x in list:=",d.values())
v=d[x]
print(v)
#find the location of x in
list.
L2=[]
d=dict()
d[x]=0
count=1
for ch in L1:
if x==int(ch):
L2.append(count)
count+=1
print("Location of x in List :=", L2)

dict1=dict()
dict1.update({x:[v, L2]})
print("Location of x in List :=", dict1)

Run part:-
the elements in List L1 [3, 11, 2, 2, 1, 3, 11, 3, 3]
Frequency of x in list:= dict_values([4])
4
Location of x in List := [1, 6, 8, 9]
Location of x in List := {3: [4, [1, 6, 8, 9]]}
# Write a python program to pass a list to
a function and double the odd values and
half even values of a list and display list
element after changing.
def listprocess(L1):
length=len(L1)
print(length)
for i in range(0,length):
if(i%2==0):
L1[i]=L1[i]*2
else:
L1[i]=L1[i]/2
return(L1)

#__main__
'''
L1=[]
n=int(input("enter the number of elements ="))
for i in range(n):
item = int(input('Enter No. ='))
L1.append(item)
'''
L1=[1,2,3,4,5,6]

print("the elements in List L1",L1)


L=listprocess(L1)
print(L)
Run part:-
the elements in List L1 [1, 2, 3, 4, 5, 6]
6
[2, 1.0, 6, 2.0, 10, 3.0]
# Write a python program to input n
numbers in tuple and pass it to a
function to count how many even
and odd numbers are entered.
def counter(T):
length=len(T)
print("Length of tuple is :-", length)
counteven=0
countodd=0
for i in range(0,length):
if T[i]%2==0:
counteven+=1
else:
countodd+=1
print("\nTotal even numbers are :=", counteven)
print("Total odd numbers are :=",countodd)

#__main__
# creation of tuple using list
L1=[]
n=int(input('ENTER THE NUMBER OF ELEMENTS :'))
for i in range(n):
print('Enter ', i+1 , ' element= ',end=' ')
element = int(input())
L1.append(element)

print("The list 1 is : ",L1)


T1=tuple(L1)
# creation of tuple from list
T1=tuple(L1) # ONLY ONE ARGUMENT
print("\nThe tuple is : ",T1)
counter(T1)
Run Part:-

ENTER THE NUMBER OF ELEMENTS :5

Enter 1 element= 1
Enter 2 element= 2
Enter 3 element= 3
Enter 4 element= 7
Enter 5 element= 8
The list 1 is : [1, 2, 3, 7, 8]

The tuple is : (1, 2, 3, 7, 8)


Length of tuple is :- 5

Total even numbers are := 2


Total odd numbers are := 3
#Write a python program to
create a function for a
dictionary with key & value and
update value of that
key in dictionary entered by
user.
def changevalue(sm):
x=int(input("Enter the key:="))
name=input("Enter new name:=")
age= int(input("Enter new age:="))
for k in sm.keys():
if(k==x):
sm.update({k:[name,age]})
print('PRINTING WHOLE DICTIONARY IN
FUNCTION\n',sm)
#__main__
'''
#DECLARATION OF A BLANK DICTIONARY
studentmark= {}
#input in run time
n=int(input('ENTER THE NUMBER OF
ELEMENTS\t :'))
for i in range(n):
print('\nEnter ', i+1 , ' element=
',end='\n')

rollno= int(input("Enter the Rollno\


t:"))

name = input('Enter the name\t:')

age = input('Enter the age\t:')

studentmark[rollno]=[name,age]
'''
studentmark={100:['ram','10'], 200:
['laxman,20']}

# PRINTING WHOLE DICTIONARY

print('PRINTING WHOLE DICTIONARY\


n',studentmark)
# find the length using len()
length=len(studentmark)
print('\nfind the length using len() =' ,
length)

changevalue(studentmark)
print('PRINTING WHOLE DICTIONARY\
n',studentmark)

Run Part:-
PRINTING WHOLE DICTIONARY
{100: ['ram', '10'], 200: ['laxman,20']}

find the length using len() = 2


Enter the key:=200
Enter new name:=vijay
Enter new age:=25
PRINTING WHOLE DICTIONARY IN
FUNCTION
{100: ['ram', '10'], 200: ['vijay', 25]}
PRINTING WHOLE DICTIONARY
{100: ['ram', '10'], 200: ['vijay', 25]}
'''Write a python program which
counts vowels in a string using user
defined function.
For example :-
For given input string - this is a book
The output should be - 5 '''
def countvowel(s):
vow="aeiouAEIOU"
ctr=0
for ch in s:
if ch in vow:
ctr=ctr+1
print ("The total vowels are :",ctr)
def countallvowel(s):
ctr=0
for i in s:
if (i=='A' or i=='a' or i=='E' or i=='e' or i=='I'or
i=='i' or i=='O' or i=='o' or i=='U'or i=='u'):
ctr=ctr+1
return ctr

#__main__
#s=input("Enter the string")
s="this is a book"

print("The given string is\n",s)


countvowel(s)
x=countallvowel(s)
print ("The total vowels are :",x)
Run Part:-
The given string is

this is a book
The total vowels are : 5
The total vowels are : 5
# Write a program in python to
generate random numbers
between 1 and 6.

import random

print("random number between 1 and 6")

print("\nrandint(a,b) return a random


integer between a and b")

print(random.randint(1,6)) # we may get 1


and 6 also

Run Part:-
random number between 1 and 6

randint(a,b) return a random integer


between a and b
5
# Write a program in python to explain
mathematical functions-len-pow-str-int-
float-range-type-abs-divmod-sum.
st="this"
print("the length of st is :=", len(st))

x=pow(2,3) #1
print(x)

a=123.45
STR=str(a)
print(STR)

b=float(STR) #2
print(b)

c=int('15') #3
print(c)

print(range(5))

print(type(c))
d=-15
print("absolute value :=", abs(d)) #4

print("quotient and
remainder:=" ,divmod(9,5)) # return
quotient and remainder #5

print(sum([1,2,3]))
print(sum((1,2,3)))
print(sum([1,2,3],5))
Run part:-
the length of st is := 4
8
123.45
123.45
15
range(0, 5)
<class 'int'>
absolute value := 15
quotient and remainder:= (1, 4)
6
6
11
# Write a program in python to
explain mathematical functions-max-
min-oct-hex-round.
print("max")
print(max([5,7,6],[2,3,4])) # match first
element only of both lists
print(max([5,7,6],[7,4,3]))
print(max((5,7,6),(2,3,4))) # match first
element only of both tuples

print("min")
print(min([5,7,6],[2,3,4])) # match first
element only of both lists
print(min([5,7,6],[7,4,3]))
print(min((5,7,6),(2,3,4))) # match first
element only of both tuples

print(oct(10))

print(hex(10))
print(hex(15))
x=7.5550
y=int(x)
print(y)

z=round(x)
print(z)

p=round(x,2)
print(p)
Run part:-
Max

[5, 7, 6]
[7, 4, 3]
(5, 7, 6)
min
[2, 3, 4]
[5, 7, 6]
(2, 3, 4)
0o12
0xa
0xf
7
8
7.55
# Write a program in python to explain
string functions-join-split-replace.
#join only joins strings
st1="#"
print(st1.join("Student")) # joind string

st2="##"
print(st2.join("Student"))

st3="##"
print(st3.join(["good", "morning", "all"])) # join
with list

st4="##"
print(st3.join(("good", "morning"))) # join with
tuple

#st4="##"
#print(st3.join((777, "good", "morning"))) # show
errors- only string allowed in tuple

#split makes list


st5="this is a book"
print(st5.split()) # split at spces in list form
st6="this is a ice-cream"
print(st6.split("i")) # split at 'i'

#replace
st7="this is a book"
print(st7.replace('is','are')) #find and replace

#capitalize
st8="this is a book"
print(st8.capitalize()) # capital first letter of a
string

Run part:-
S#t#u#d#e#n#t

S##t##u##d##e##n##t
good##morning##all
good##morning
['this', 'is', 'a', 'book']
['th', 's ', 's a ', 'ce-cream']
thare are a book
This is a book
# Write a program in python to
explain string constant function.
import string

print("print all alphabet in lowercase and


uppercase")
print(string.ascii_letters)

print("\nprint all alphabet in lowercase")


print(string.ascii_lowercase)

print("\nprint all alphabet in uppercase")


print(string.ascii_uppercase)

print("\nprint all digits")


print(string.digits)

print("\nprint all hexadecimal")


print(string.hexdigits)

print("\nprint all octal")


print(string.octdigits)

print("\nprint all punctuation")


print(string.punctuation)
st1="this is a book"
print("\nmake each word of a string capital")
print(string.capwords(st1)) # capwords()=
split()+capitalize()+join()

Run part:-
print all alphabet in lowercase and uppercase

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM
NOPQRSTUVWXYZ

print all alphabet in lowercase


abcdefghijklmnopqrstuvwxyz

print all alphabet in uppercase


ABCDEFGHIJKLMNOPQRSTUVWXYZ

print all digits


0123456789
print all hexadecimal
0123456789abcdefABCDEF
print all octal
01234567
print all punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

make each word of a string capital


This Is A Book
# Write a program in python to
make a user defined module for an
arithmetic calculator.
Cal.py file

def calculator(x,y,ch):
if(ch=='+'):
c=a+b
elif(ch=='-'):
c=a-b
elif(ch=='*'):
c=a*b
elif(ch=='/'): # float quotient
c=a/b
elif(ch=='//'): #integer quotient
c=a//b
elif(ch=='%'): # remainder
c=a%b
return c
our main file :-
import cal
#__main__
a=9
b=2
x=calculator(a,b,'%')
print(x)

Run part:-
1
# Write a program in python to read a
text line by line and display each word
separated by #.

# make one.txt file on drive and give path


in below line.
myfilein = open('one.txt','r')
str=' ' # must have ateast one space or
one character or any thing

while str:
str= myfilein.readline()
words = str.split()
for i in words:
print (i,"#",end='')
print()

myfilein.close()

content of one.text file:-


hello students
this is a book
that is my book
this is mobile

Run part:-
hello #students #

this #is #a #book #

that #is #my #book #

this #is #mobile #


#Write a python program to copy all the
lines excepts the lines which contain the
character 'a' from a
file named "article.txt" to another file
named "copy.txt".

myfilein = open('article.txt','r')
myfileout = open('copy.txt','w')

str=' ' # must have ateast one space


while str:
str= myfilein.readline()

if 'a' not in str:


print(str,end='')
myfileout.write(str)

myfilein.close()
myfileout.close()

Contents of article.txt file:-


hello students
this is a book
that is my book
this is mobile

Run part:-
hello students

this is mobile

Contents of copy.txt file:-


hello students

this is mobile
# Write a python program to read
characters from keyboard one by one,
then store all lowercase letters
inside a file "LOWER", all uppercase
letters gets inside a file "UPPER" and
other characters inside file
"OTHERS".

myfile1 = open('LOWER.txt','w')
myfile2 = open('UPPER.txt','w')
myfile3 = open('OTHERS.txt','w')

Llower=[] # creation of blank list


Lupper=[]
Lothers=[]

str= input("Enter the contents:=")


for ch in str:
if ch >= 'a' and ch <='z':
Llower.append(ch)
elif ch >='A' and ch<='Z':
Lupper.append(ch)
else:
Lothers.append(ch)
print("Contents in LOWER FILE:-", Llower)
print("Contents in UPPER FILE:-",Lupper)
print("Contents in OTHER FILE:-",Lothers)

myfile1.writelines(Llower)
myfile2.writelines(Lupper)
myfile3.writelines(Lothers)

myfile1.close()
myfile2.close()
myfile3.close()

Run part:-

Enter the contents:=These are 10 apples.


Contents in LOWER FILE:- ['h', 'e', 's',
'e', 'a', 'r', 'e', 'a', 'p', 'p', 'l', 'e', 's']
Contents in UPPER FILE:- ['T']
Contents in OTHER FILE:- [' ', ' ', '1', '0',
' ', '.']
#Write a program in python to create a
binary file with rollno and name. Search
for a given roll number
and display name, if not found display
appropriate message.

import pickle
#class declaration
class student:
def __init__(self, rno = 0 , nm = "" ):
self.rollno=rno
self.name=nm

def getdetails(self):
print("Enter the details\n")
self.rollno=input("Enter the rollno.:=")
self.name=input("Enter the name:=")
def show(self):
print("\n\nReport of students are:\n")
print("The Roll Number of student is: ",
self.rollno)
print("The name of student is : ",
self.name)
def getrollno(self):
return int(self.rollno)

# object creation
object1= student(1,"ram")
object1.show()

object2= student()
object2.getdetails()
object2.show()

#Writing object1 on binary file.


myfile = open("Student.log","wb")
pickle.dump(object1,myfile) # writing the
dictionary in student.log file.
# dump() having two
arguments.
pickle.dump(object2,myfile)
myfile.close()

# reopen the binary file in read mode


myfile = open("Student.log","rb")
r=int(input("Enter the rollno to be
searached"))
flag=0
try:
while True:
object3=pickle.load(myfile) #
load() raise EOF error when it reaches
end of file.
y = object3.getrollno()
if(r==y):
object3.show()
flag=1
except EOFError:
if(flag==0):
print("record not found")
myfile.close()
Run part:- ( the record of one student is taken
in compile time and second one is taken in
run time. )

Report of students are:


The Roll Number of student is: 1
The name of student is : ram
Enter the details
Enter the rollno.:=2
Enter the name:=laxman

Report of students are:


The Roll Number of student is: 2
The name of student is : laxman

Enter the rollno to be searached1

Report of students are:


The Roll Number of student is: 1
The name of student is : ram

You might also like