0% found this document useful (0 votes)
85 views

CS Practical

The document provides code snippets for various Python functions including searching and modifying lists, tuples, dictionaries, strings, and files. It includes functions to search for elements in lists, count even and odd numbers, update dictionary values, count vowels in strings, and remove lines containing a character from one file and write to another. The functions demonstrate passing arguments to functions, returning values, and performing common list, string, and file operations.

Uploaded by

Devvrat Solanki
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)
85 views

CS Practical

The document provides code snippets for various Python functions including searching and modifying lists, tuples, dictionaries, strings, and files. It includes functions to search for elements in lists, count even and odd numbers, update dictionary values, count vowels in strings, and remove lines containing a character from one file and write to another. The functions demonstrate passing arguments to functions, returning values, and performing common list, string, and file operations.

Uploaded by

Devvrat Solanki
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/ 8

1.

To write a python program to search an element in a list and display the frequency of
elements present in the list and their location using Linear search by using a user

defined function

linsearch(listt,element):
count=0
for i in range(0,len(listt)):
if listt[i]==element:
count+=1
print("Element found at position",i+1,"position")
if count==0:
print("No such element is found")
else:
print("the number of times the element appeared in the
list:",count)
L=eval(input("Enter a list:"))
E=int(input("Enter the element to be searched in the list:"))
linsearch(L,E)

2.To write a python program to search an element in a list and display the frequency of
elements present in the list and their location using binary search by using a user
defined function.

def Bsearch(mylist,item):
low=0
high=len(mylist)-1
while(low<=high):
mid=(low+high)//2
if mylist[mid]==item:
return mid
elif mylist[mid]>item:
high=mid-1
else:
low=mid+1
return -1
List2=eval(input("Enter a list in sorted form:"))
element=int(input("Enter the element to be sorted:"))
s=Bsearch(List2,element)
if s+1==0:
print("Element not found")
else:
print("The element is found at position",s+1)
3.To 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 elements after changing.

def change(List):
for i in range(0, len(List)):
if List[i] % 2 == 0:
List[i] = List[i] / 2
else:
List[i]=List[i]* 2
return List

L = eval(input("Enter a list containing numbers:"))


L2 = change(L)
print("The changed list is:", L2)

4.To write a Python program input n numbers in tuple and pass it to function to count how
many even and odd numbers are entered

def count(tuple):
counteven = 0
countodd = 0
for i in range(0, len(tuple)):
if tuple[i] % 2 == 0:
counteven += 1
else:
countodd += 1
print("The number of even numbers in this tuple is", counteven)
print("The number of odd numbers in this tuple is", countodd)

T = eval(input("Enter a tuple containing numbers:"))


count(T)

5.To write a Python program to function with key and value, and update value at that key
in the dictionary entered by the user.
def update_dictionary(dictionary,key):
value=input("Enter the value to be updated:")
dictionary[key]=value
return dictionary
D=eval(input("Enter a dictionary:"))
K=eval(input("Enter the key to be updated:"))
print("The unupdated dictionary is:",D)
update=update_dictionary(D,K)
print("The updated dictionary is",update)
6.To write a Python program to pass a string to a function and count how many vowels
present in the string.

def count_vowel(str):
count=0
for i in range(0,len(str)):
if str[i] in ["a","e","i","o","u","A","E","I","O","U"]:
count+=1
return count
strl=input("Enter a string:")
c=count_vowel(strl)
print("The number of vowels present in the given string is:",c)

7.To write a Python program to generate (Random Number) that generates random
numbers between 1 and 6 (simulates a dice) using a user defined function.

import random
def dice():
num=random.randint(1,6)
print("The number on the dice is:",num)
Chances=int(input("Enter the number of times dice is to be thrown: "))
for i in range (Chances):
dice()
a=input()
8. To write a menu driven python program to implement 10 python mathematical functions.

import math
print("""The Menu for implementing mathematical functions is as follows:
1.Modulus
2.Square Root
3.Greatest Integer
4.Smallest Integer
5.Power
6.Greatest common divisor
7.Factorial
8.Floor Division
9.Remainder
10.Round Off""")
choice=int(input("Enter your choice:"))
if choice in [1,2,3,4,7]:
n=float(input("Enter the number:"))
if choice==1:
print("The modulus of",n,"is",math.fabs(n))
if choice==2:
print("The square root of",n,"is",math.sqrt(n))
if choice==3:
print("The greatest integer of",n,"is",math.floor(n))
if choice==4:
print("The smallest integer of",n,"is",math.ceil(n))
if choice==7:
print("The factorial of",n,"is",math.factorial(n))
elif choice in [5,6,8,9,10]:
n1=float(input("Enter the first number: "))
n2=float(input("Enter the second number:"))
if choice==5:
print("The result is:",math.pow(n1,n2))
if choice==6:
print("The greatest common divisor is",math.gcd(int(n1),int(n2)))
if choice==8:
print("The floor division is",(n1//n2))
if choice==9:
print("the remainder is",(n1%n2))
if choice==10:
print("the rounded off number is",round(n1,int(n2)))
else:
print("Not a valid choice...!!!Please make a valid choice")
9.To write a python program to implement python string functions.

strl="i love my country"


print(strl*4)
print(strl+"India")
print("Love"in strl)
print(strl.capitalize())
print(strl.find("ov"))
print(strl.isalnum())
print(strl.isalpha())
print(strl.isdigit())
print(strl.isspace())
print(strl.islower())
print(strl.isupper())
print(strl.istitle())
print(strl.startswith("i"))
print(strl.endswith("try"))
print(strl.swapcase())
print(strl.partition("my"))
print(strl.count("y"))
print(strl.lstrip("i"))
print(strl.rstrip("country"))
print("***".join("Trial"))
print("###".join(["trial","hello","new"]))
print(strl.split("0"))
print(strl.replace("country","nation"))

10.To write a menu driven program in python to delete the name of a student from the
dictionary and to search phone no of a student by student name.

print('''the menu is as following:


1.Delete from dictionary
2.Search phone number using the name from dicitonary
3.Exit''')
Dict={"Lisa":4365876894 , "Ann":875476546 , "Jayden":735423240 ,
"James":8357598465 }
print("""The dictionary contains details of:
1.Lisa 2.Ann 3.Jayden 4.James""")
choice=int(input("enter your choice:"))
if choice==1:
name=input("enter the name of student whose data is to be deleted:")
del Dict[name]
print("deleted successfully.....!!!!!")
print("the updated dictionary is: ")
print(Dict)
elif choice==2:
name=input("enter the name of the stuedent whose data is to be
searched:")
print("phone number of ",name,"is" ,Dict[name])
elif choice==3:
print("Existing.....")
else:
print("Not a valid choice....!!")
11.To write a python program to read and display file content line by line with each word
separated by #.
fileout=open("my file.txt","r")
line=" "
while line:
line=fileout.readline()
for word in line.split():
print(word,end="#")
print()
fileout.close()

12.To write a python program to read a text file and display the number of consonants, vowels, uppercase,
lowercase characters in the file.
myfile=open("My File.txt","r")
ch=" "
vcount=0
ccount=0
lcount=0
ucount=0
while ch:
ch=myfile.read(l)
if ch in ["a","e","o","u","i","A","E","U","O","I"]:
vcount+=1
elif ch.isalpha():
ccount+=1
if ch.islower():
lcount+=1
else:
ucount+=1
print("The number of vowels in the file:",vcount)
print("The number of consonants in the file:",ccount)
print("The number of lowercase characters in the file:",lcount)
print("The number of uppercase characters in the file:",ucount)
13.To write a Menu driven program in python to count spaces, digits, words and lines
from text file TOY.txt
lcount=len(s)
for line in s:
l=line.split()
wcount+=len(1)
myfile.seek(1)
while ch:
ch=myfile.read(1)
if ch.isspace():
scount+=1
elif ch.isdigit():
dcount+=1
myfile.close()

print("The number of lines in the file is",lcount)


print("The number of words in the file is",wcount)
print("The number of spaces in the file is",scount)
print("The number of digits in the file is",dcount)

14.To write a python program to remove all the lines that contain the character „a‟ in a file and write it to
another file.
file1=open("My File.txt","r")
file2=open("Filetwo.txt","w")
l1=file1.readlines()
for line in l1:
if "a" not in line:
file2.write(line)
file2.write("/n")
file1.close()
file2.close()
print("Work completed successfully")
15.To write a python program to create a binary file with name and roll number. Search for
a given roll number and display name, if not found display appropriate
message. import pickle
f1=open("studentfile.dat","wb")
stu={}
n=int(input("enter the number of student whose data is to be searched:"))
for i in range(n):
print("enter the data of student",i+1)
rno=int(input("enter the roll no."))
name=input("enter the roll student")
stu["name"] = name
stu["roll no"]=rno
pickle.dump(stu,f1)
f1.close()
r2=int(input("enter the roll number to be searched:"))
stu2={}
found=False
fin=open("stedentfile.dat","rb")
try:
while True:
stu2=pickle.load(fin)
if stu2["roll no"]==r2:
print("the number of student is: ",stu2["name"])
found=True
except EOFError:
if found==True:
print("search successful")
elif found==False:
fin.close()

You might also like