DELHI PUBLIC
SCHOOL
KALYANPUR KANPUR
. COMPUTER SCIENCE
PRACTICAL FILE
SUBMITTED TO SUBMITTED
BY HIMANSHU SIR ADITYA VIKRAM SINGH
........................................................OF 11S4
....................................
....................
FLOW OF CONTROL
Ques1 Program that takes a number and
checks whether the given number is odd or even .
num=int(input(“Enter an integer:”))
if num%2==0:
print(num, “is EVEN number.”)
else:
print(num, “is ODD number.”)
OUTPUT
Enter an integer – 8
8 is EVEN number
---------------------------------------------------------------------------------------
-
Ques2 Program to accept three integers and print the largest of
the three. Make use of only if statement.
x=y=z=0
x=float(input(“Enter first number:”))
y=float(input(“Enter second number.”))
z=float(input(“Enter third number.”))
max=x
if y > max :
max=y
if z > max :
max=z
print(“Largest number is”, max)
OUTPUT
Enter first number = 7.235
Enter second number = 6.99
Enter third number = 7.533
Largest number is 7.533
---------------------------------------------------------------------------------------
-
Ques3 Program to test the divisibility of a
number with another number.
number1 = int(input(“Enter first number :”))
number2 = int(input(“Enter second number :”))
remainder = number1%number2
if remainder == 0 :
print(number1,”is devisible by”, number 2)
else :
print(number1,”is not divisible by”, number2)
OUTPUT
Enter first number = 119
Enter second number = 3
119 is not divisible by 3
===================
Enter first number = 119
Enter second number = 17
119 is divisible by 17
---------------------------------------------------------------------------------------
-
Ques4 Program that reads two number and an arithmetic
operator and displays the computed result .
num1 = float(input(“Enter first number :”))
num2 = float(input(“Enter second number :”))
op = input(“Enter operator [ + - * / % ] :”)
result = 0
if op == ‘’+’ :
result = num1 + num2
elif op == ‘’ -‘’ :
result = num1 - num2
elif op == ‘’*’ :
result = num1*num2
elif op == ‘’/’ :
result = num1%num2
else :
print(“Invalid operator !!”)
print(num1, op, num2, ‘’=’, result)
OUTPUT
Enter first number - 5
Enter second number – 2
Enter operator [ + - * / % ] : *
5.0*2.0 = 10.0
------------------------------------------------------------------------------
Ques5 Program to print whether a given character is an
uppercase or a lowercase character or a digit or any other
character .
Ch= input(“Enter a single character :”)
If ch>=’A’ and ch<=’Z’ :
Print(“You entered a lower case character .”)
Elif ch>=’0’ and ch<=’9’ :
Print(“You entered a digit.”)
else :
print(“You entered a special character .”)
OUTPUT
Enter a character – 5
You entered a digit .
---------------------------------------------------------------------------------------
-
Ques6 Program to calculate and print roots ax2+bx+c=0 (a/=0) .
Print(“For quadratic equation, ax**2+bx+c=0, enter coefficients below”)
a=int(input(“Enter a :”))
b=int(input(“Ener b :”))
c=int(input(“Enter c :”))
if a==0 :
print(“Value of”, a, ‘’should not be zero’)
print(“\n Aborting !!!!!”)
else :
delta = b*b-4*a*c
if delta>0 :
root1=(-b+math.sqrt(delta))/(2*a)
root2=(-b-math.sqrt(delta))/(2*a)
print(“Roots are REAL and UNEQUAL”)
print(“Roots1=”, roots1,“<Roots2=”, root2)
elif delta ==0 :
root1= -b/(2*a);
print(“Roots are REAL and EQUAL”)
print(“Root1 =”, root1, ‘”, Root2=”, root1)
else:
print(“Roots are complex and imaginary”)
OUTPUT
For quadratic equation, ax**2 + bx + c = 0, enter coefficients below
Enter a : 3
Enter b : 5
Enter c : 2
Roots are REAL and UNEQUAL
Root1=-0.666666666667, Root = -1.0
---------------------------------------------------------------------------------------
LIST MANIPULATION
Ques1 Write a program to createv a copy of list. In the lists copy , add
10 to its first and last elements . Then display the lists.
L1 = [ 17, 24, 15, 30, 34, 27 ]
L2 = L1.copy()
print(“Origional list :”, L1 )
print(“Created copy of the list :”, L2)
L2[0] += 10
L2[-1] += 10
print9”Copy of the list after changes :”, L2)
print(:Original list :”, L1)
OUTPUT
Original list – [ 17, 24, 15, 30, 34, 27]
Created copy of the list –[17, 24, 15, 30, 34, 27]
Copy of the list after changes – [27, 24, 15, 30, 34, 37]
Original list – [ 17, 24, 15, 30, 34, 27]
---------------------------------------------------------------------------------------
Ques2 Write to find frequencies of all elements of a list. Also,
print the list of uniqye elements in list and duplicate elements in
the given list.
1st = eval(input(“Enter list :”))
Length = len(1st)
uniq = []
dupl = []
count = I = 0
while I < length :
element = 1st [i]
count = 1
if element not in uniq and element not in dupl :
I +=1
For j in range(I, length ):
If element == 1st[j]
Count +=1
else:
print(“Element”, element, “frequency:”, count )
if count ==1:
uniq.append(element)
else:
dupl.append(element)
else:
I +=1
print(“Original list”, unq)
print(“Unique elements list”,uniq )
print(“Duplicates elements list”, dupl)
OUTPUT
Enter list – [2, 3, 4, 5, 3, 6, 7, 3, 5, 2, 7, 1, 9, 2]
Element 2 frequency – 3
Element 3 frewquency – 3
Element 4 frequency – 1
Element 5 frequency – 2
Element 6 frequency – 1
Element 7 frequency – 2
Element 1 frequency – 1
Element 9 frequency – 1
Original list [2, 3, 4, 5, 3, 6, 7, 3, 5, 2, 7, 1, 9, 2]
Unique elements list [4, 6, 1, 9]
Duplicates elements list [2, 3, 5, 7]
---------------------------------------------------------------------------------------
Ques3 Write a program to check if the maximum element of the
list lies in the first half of the list or in second half.
1st = eval(input("Enter a list:"))
In = len(1st)
mx = max(1st)
ind 1st.index(mx) =
if ind <= (In/2):
print("The maximum element", mx, "lies in the 1st half.")
else:
print("The maximum element", mx, "lies in the 2nd half.")
OUTPUT
Enter a list: [6, 8, 11, 6, 12, 7, 16]
The maximum element 16 lies in the 2nd half.
---------------------------------------------------------------------------------------
Ques4 Write a program to input two lists and display the
maximum element from the elements of both the lists combined,
along with its index in its list.
1st1-eval(input("Enter list1:"))
1st2= eval(input("Enter list2:"))
m * 1 = max(1st * 1)
m * 2 = ma(1st * 2)
if mx * 1 >= m * 2
print(mx1, "the maximum value is in list1 at index", 1stl.index (mx1))
else:
print(mx2, "the maximum value is in list2 at Index", 1st2.index(mx2))
OUTPUT
Enter list1: [6, 8, 11, 6, 12, 7, 16]
Enter list2: [34, 11, 23, 11]
34 the maximum value is in list? at index 0
---------------------------------------------------------------------------------------
Ques5 Write a program to input a list of numbers and test if a
number is equal to the sum of the cubes of its digits. Find the
smallest and largest such number from the given list of numbers.
val = eval input("Enter a list :"))
alist = []
s = len(val)
for i in range (s):
num = val [i]
csum=0
while num:
dignum % 10
csum += (dig dig "dig)
num num // 10
if csum == val[1]:
alist.append(val[1])
print("Largest number (= sum of its digits' cubes):", max(alist))
print("Smallest number (= sum of its digits' cubes):", min(alist))
OUTPUT
Enter a list :[67, 153, 311, 96, 370, 4050, 371, 955, 407]
Largest number (= sum of its digits' cubes): 407
Smallest number (= sum of its digits' cubes) : 153
---------------------------------------------------------------------------------------
Ques6 Write a program to input a list Ist and two numbers M
and N. Then create a list from those Ist elements which are
divisible by both M and N.
1st eval(input("Enter a list:"))
1st * 2 =[]
M, N = eval(input("Enter two numbers as M, N :")) for num in 1st:
if( num % M = 0 and num \% N ==0) :
1st2.append(num)
print("New created list is :", 1st2)
Enter a list: [6, 8, 11, 6, 12, 7, 16]
Enter two numbers as M, N : 6,2
New created list is: [6, 6, 12]
---------------------------------------------------------------------------------------
STRING MANIPULATION
Ques1 Write a program that inputs a line of text and prints its
each word in a separate line. Also, print the count of words in
the line.
s = input("Enter a line of text :") print("Total words : ", count)
count = 0
for word in s.split():
print(word)
count += 1
OUTPUT
Enter a line of text: Python is fun.
Python
is
fun.
Total words : 3
---------------------------------------------------------------------------------------
Ques2 Program that reads a line and a substring. It should then
display the number of occurrences of the given substring in the
line.
line input("Enter line :")
sub= input("Enter substring :")
length = len(line)
lensub = len(sub)
start count = 0
end = length
while True:
pos = line.find(sub, start, end)
if pos != -1:
count += 1
start = pos+ lensub
else:
break
if start >= length:
break
print ("No. of occurrences of", sub, ':', count)
OUTPUT
Enter line : jingle bells jingle bells jingle all the way Enter substring:
jingle
No. of occurrences of jingle : 3
---------------------------------------------------------------------------------------
Ques3 Write a program that inputs a string that contains a
decimal number and prints out the decimal part of the number.
For instance, if 515.8059 is given, the program should print out
8059.
s=input("Enter a string (a decimal number) :')
t-s.partition('.')
print("Given string: ", s)
print("part after decimal", t[2])
OUTPUT
Enter a string (a decimal number):515.8059
Given string: 515.8059
part after decimal 8059
---------------------------------------------------------------------------------------
Ques4 Write a program that inputs individual words of your
school motto and joins them to make a string should also input
day, month and year of your school's foundation date and print
the complete date.
print("Enter words of your school motto, one by one")
w1 = input("Enter word 1:")
w2 = input("Enter word 2: ")
w3= input("Enter word 3:")
w4= input("Enter word 4:").
motto "".join( [w1, w2, w3, w4])
print("Enter your school's foundation date.")
dd = input("Enter dd:") mm = input("Enter mm:")
yyyy = input("Enter yyyy:")
dt "/".join( [dd, mm, yyyy])
print("School motto:", motto)
print("School foundation date: ", dt)
OUTPUT
Enter words of your school motto, one by one
Enter word 1:world
Enter word 2:15 Enter word 3:a
Enter word 4: family.
Enter your school's foundation date.
Enter dd:01
Enter mm:10
Enter yyyy: 1975
School motto : world is family
School foundation date : 01/10/1975
---------------------------------------------------------------------------------------
Ques5 Write a program to input a string and check if contains a
digit or not .
strg input("Enter a string :")
test= False
dig =^8123456789^
for ch in strg:
if ch in dig:
print("The string contains a digit.a")
test = True
break
if test False:
print("The string doesn't contain a digit.")
OUTPUT
Enter a string : rf67
The string contains a digit.
---------------------------------------------------------------------------------------
-
Ques6 Write a program to input an address containing a
pincode and extract and print the pincode from the input
address.
add input("Enter text:")
i=0
ln= len(add)
#for ch in add:
while i < 1n
if ch.isdigit():
sub = add[i: (1+6)]
ch = add[i] if sub.isdigit(): print(sub) break
i +=1
OUTPUT
Enter text:New Delhi, 110001 110001
---------------------------------------------------------------------------------------
TUPLES
Ques1 Write a program to check if the elements in the first half
of a tuple are sorted in ascending order or not.
tup = eval(input("Enter a tuple : "))
In = len(tup) mid = 1n//2
if ln % 2 == 1:
mid = mid+1
half = =tup[:mid]
if sorted (half) == list(tup[:mid]):
print("First half is sorted")
else:
print("First half is not sorted")
OUTPUT
Enter a tuple: 11, 12, 13, 14, 10,
First half is sorted
------------------------------------------------------------------------------
Ques2 Write a program to check if all the elements of a tuple are
in descending order or not.
tup = eval (input("Enter a tuple: "))
if sorted(tup, reverse = True) == list(tup):
print("Tuple is sorted in descending order.")
else:
print("Tuple is not sorted in descending order.")
OUTPUT
Enter a tuple: 22, 20, 18, 17, 15, 12
Tuple is sorted in descending order.
---------------------------------------------------------------------------------------
Ques3 A tuple stores marks of a student in 5 subjects. Write a
program to calculate the grade of the student as per the
following:
Average grade
>=75 A
60-74.999 B
50-59.999 C
<50 D
mks eval(input("Enter marks tuple: "))
total = sum(mks)
avg = total /5
if avg >= 75:
grade = 'A'
elif avg >= 60:
grade = 'B'
elif avg >= 50:
grade = 'C'
else:
grade = 'D'
print("Total Marks: ", total, "Grade:", grade)
OUTPUT
Enter marks tuple: 78.5, 67.8, 89.9, 70.5, 50 Total Marks: 356.70 Grade:
------------------------------------------------------------------------------
Ques4 Write a program to input names of n students and store
them in a tuple. Also, input a name from the user and find if this
student is present in the tuple or not.
1st = []
n=int(input("How many students?"))
for i in range(1, n+1):
name = input("Enter name of student" + str(1)+" : ")
1st.append(name)
ntuple tuple(1st)
nm input("Enter name to be searched for :")
if mm in ntuple:
print (nm, "exists in the tuple")
else:
print(nm, "does not exist in the tuple")
OUTPUT
How many students?5
Enter name of student 1: Anaya
Enter name of student 2: Anusha
Enter name of student 3: Kirat
Enter name of student 4: Kyle
Enter name of student 5: Suji
Enter name to be searched for: Suji Suji exists in the tuple
---------------------------------------------------------------------------------------
Ques5 Write a program to input a tuple and check if it contains
the all elements as same
tup = eval (input("Enter a tuple: "))
In = len(tup)
num=tup.count(tup[0])
if num == In:
print("Tuple contains all the same elements.")
else:
print("Tuple contains different elements.")
OUTPUT
Enter a tuple: 23,23,23,23
Tuple contains all the same elements.
---------------------------------------------------------------------------------------
Ques6 Write a program to input a 4-element tuple and unpack it
to four variables. Then recreate the tuple with elements swapped
as 1st element with 3rd and the 2nd element with the 4th
element.
tup eval(input("Enter a 4 element tuple: "))
a,b,c,d=tup
print("Tuple unpacked in", a, b, c, d)
tup = c, d, a, b
print("Tuple after swapping the elements: ", top)
OUTPUT
Enter a 4 element tuple: 10, 20, 30, 40 Tuple unpacked in 10 20 30 40
Tuple after swapping the elements: (30, 40, 10, 20)
------------------------------------------------------------------------------
DICTIONARIES
Ques1 Write a program to read roll numbers and marks of four
students and create a dictionary from it having roll numbers as
keys.
rno = []
mks = []
for a in range(4):
r, m = eval(input("Enter Roll No., Marks :")) rno.append(r)
mks.append(m)
d = {rno[0]: mks[0], rno[1]: mks[1], rno[2]:mks[2], rno[3]:mks[3]}
print("Created dictionary")
print(d)
OUTPUT
Enter Roll No., Marks: 1, 67.5
rno = []
mks = []
Enter Roll No., Marks: 2, 45.6
Enter Roll No., Marks: 3, 78.4 Enter Roll No., Marks: 4, 70.5
Created dictionary
[1: 67.5, 2: 45.6, 3: 78.4, 4: 70.5}
------------------------------------------------------------------------------
Ques2 Write a program to create a dictionary M which stores the
marks of the students of class with roll numbers as the keys and
marks as the values. Get the number of students as input.
M = {}
n = int(input("How many students?")
for a in range(n):
r, m = eval(input("Enter Roll No., Marks :"))
M[r] = m
print("Created dictionary")
print (M)
OUTPUT
How many students? 5
Enter Roll No., Marks :1, 67.3
Enter Roll No., Marks :2, 54.5
Enter Roll No., Marks :3, 77.9
Enter Roll No., Marks :4, 89.9
Enter Roll No., Marks :5, 83.5
Created dictionary
{1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9, 5: 83.5}
Ques3 Write a program to create a dictionary containing names
of competition winner students as keys and number of their wins
as values.
n = int(input("How many students ?"))
CompWinners = {} for a in range(n) :
key = input ("Name of the student :")
value = int (input("Number of competitions won :"))
CompWinners [key] = value
print ("The dictionary now is :")
print (CompWinners)
OUTPUT
How many students ? 5
Name of the student : Rohan
Number of competitions won
Name of the student : Zeba
Number of competitions won : 3
Name of the student : Nihar
Number of competitions won : 3
Name of the student : Roshan
Number of competitions won : 1
Name of the student: James
Number of competitions won : 5
The dictionary now is :
(Nihar': 3, 'Rohar': 5, 'Zeba: 3, Roshan': 1, "James': 5
---------------------------------------------------------------------------------------
Ques4 Consider already created dictionary M that stores roll
numbers and marks. Write a program to a roll number and delete
it from the dictionary. Display error message if the roll number
does not exist in the dictionary.
print("Created dictionary")
print (M)
rno = int(input("Roll No. to be deleted ? :"))
if rno in M:
del M[rno]
print("Roll no.", rno, "deleted from dictionary.")
else:
print("Roll no.", rno, "does not exist in dictionary.") print("Final
Dictionary")
OUTPUT
Created dictionary {1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9, 5: 83.5)
Roll No. to be deleted? :5
Roll No. 5 deleted from dictionary
Final Dictionary
{1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9}
---------------------------------------------------------------------------------------
Ques5 The dictionary S stores the roll numbers:names of the
students who have been selected to participa in national event.
Write a program to display the roll numbers selected.
print("Created dictionary")
print(S)
print("Selected roll numbers are:")
print (S.keys())
OUTPUT
(11: 'siya', 22: 'Ruby', 26: 'Keith', 31: "Preet', 32: "
dict_keys([11, 22, 26, 31, 321)
---------------------------------------------------------------------------------------
Ques6 The dictionary S stores the roll numbers:names of the
students who have been selected to participa in national event.
Modify the previous program to display the names of the
selected students
print("Created dictionary")
print(S)
print("Selected roll numbers are:")
print(S.values())
OUTPUT
{11: 'Siya', 22: 'Ruby', 26: 'Keith', 31: 'Preet", 32: "Huna"]
Selected Students' names are:
dict_values(['siya', 'Ruby', 'Keith', 'Preet', 'Huma'])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~