COMPUTER SCIENCE PYTHON
PRACTICAL FILE
Session: 2025-26
SUBMITTED TO:
NIDHI SHARMA
ROLL NO:-
CLASS:- XII (SCIENCE)
INDEX
1. Write a python Program to take input for a number, calculate and print its square and cube.
2. Write a python program to take input for 3 numbers, check and print the largest number.
3. Program to check whether a number is even or odd.
4. Program to check whether a number is divisible by 2 or 3 using nested if.
5. Menu based program to find sum, subtraction, multiplication and division of values.
6. Write a python program to take input for a number check if the entered number is Armstrong or not.
7. Program to find sum of even numbers from 1 to 7.
8. Program to find factorial of a number.
9. Program to find largest among two numbers using a user defined function.
10. Write a function DigitSum() that takes a number and returns its digit sum.
11. Program to find sum of two numbers using a user defined function with parameters.
12. Program to find simple interest using a user defined function with parameters and with return value.
13. Program to pass a list as function argument and modify it.
14. Program to sort values in a list.
15. Program to find minimum value in a list.
16. Program to check whether a value exists in dictionary.
17. Program to write rollno, name and marks of a student in a text file Marks.
18. Program to read and display contents of file [Link].
19. Program to read and display those lines from file that start with alphabet ‘T’.
20. Program to read and display those lines from file that end with alphabet ‘n’.
21. Program to count number of words in data file [Link].
22. Write a python program to read a file named
23. “[Link]”, count and print total alphabets in the file?.
24. Program to write data in a csv file [Link]. and read and display data from a csv file [Link].
25. Write a python program to maintain book details like book code, book title and price using stacks
data structures? (implement push(), pop() and traverse() functions)
26. Write a python program to maintain employee details like empno,name and salary using stacks data
structure? (implement insert(), delete() and traverse() functions)
27. Write a python program to read a file named “[Link]”, count and print the following:
(i) length of the file(total characters in file)
(ii)total alphabets
(iii) total upper case alphabets
(iv) total lower case alphabets
(v) total digits
(vi) total spaces
(vii) total special characters
28. Write a python program to read a file named “[Link]”, count and print total words starting with
“a” or “A” in the file?
[Link] a python Program to take input for a number, calculate and print its square and
cube.
CODE:
n = int(input(‘Enter a number: ’))
print(‘The square of {} is {}. ’ .format(n,n**2))
print(‘The cube of {} is {}. ’ .format(n,n**3))
OUTPUT
[Link] a python program to take input for 3 numbers, check and print the largest
number.
CODE:
num1 = float (input (“Enter first number: ”))
num2 = float (input (“Enter second number: ”))
num3 = float (input (“Enter third number: ”))
if (num1 >= num2) and (num1 >= num3) :
largest = num1
elif (num2 >= num1) and (num2 >= num3) :
largest = num2
else:
largest = num3
print(“The largest number is” , largest)
OUTPUT:
3. Program to check whether a number is even or odd.
CODE:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print ("{0} is Even".format(num))
else:
print ("{0} is odd".format(num))
OUTPUT:
4. Program to check whether a number is divisible by 2 or 3 using nested if.
CODE:
num = int(input("Enter number: "))
if num%2 == 0:
if num%3 == 0:
print ("Divisible by 3 and 2")
else:
print ("Divisible by 2 not divisible by 3")
else:
if num%3 == 0:
print ("Divisible by 3 not Divisible by 2")
else:
print ("not Divisible by 2 not Divisible by 3")
OUTPUT:
5. Menu based program to find sum, subtraction, multiplication and division of values.
CODE:
def show_choices():
print('\nMenu')
print('1. Add')
print('2. Subtract')
print('3. Multiply')
print('4. Divide')
print('5. Exit')
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
def main():
while(True):
show_choices()
choice = input('Enter choice(1-5): ')
if choice == '1':
x = int(input('Enter first number: '))
y = int(input('Enter second number: '))
print('Sum =', add(x, y))
elif choice == '2':
x = int(input('Enter first number: '))
y = int(input('Enter second number: '))
print('Difference =', subtract(x, y))
elif choice == '3':
x = int(input('Enter first number: '))
y = int(input('Enter second number: '))
print('Product =', multiply(x, y))
elif choice == '4':
x = int(input('Enter first number: '))
y = int(input('Enter second number: '))
if y == 0:
print('Error!! divide by zero')
else:
print('Quotient =', divide(x, y))
elif choice == '5':
break
else:
print('Invalid input')
main()
OUTPUT:
[Link] a python program to take input for a number check if the entered number is
Armstrong or not.
CODE:
n = int(input('Enter a number: '))
temp = n
Sum = 0
while temp > 0:
Sum += (temp % 10)**3
temp //= 10
if n==Sum:
print('{} is an armstrong number.'.format(n))
else:
print('{} is not an armstrong number.'.format(n))
OUTPUT:
[Link] to find sum of even numbers from 1 to 7.
CODE:
Sum = 0
for i in range(8):
if i % 2 == 0:
Sum += i
print('Sum of even numbers from 1 to 7 is {}.'.format(Sum))
OUTPUT:
[Link] to find factorial of a number.
CODE:
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elid num == 0:
print("the factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*1
print("The factorial of",num,"is",factorial)
OUTPUT:
[Link] to find largest among two numbers using a user defined function.
CODE:
def largest(x, y):
if x > y:
return x
else:
return y
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
result = largest(x, y)
print("Largest is: ", result)
OUTPUT:
[Link] a function DigitSum() that takes a number and returns its digit sum.
CODE:
def Digitsum(n):
temp = n
sum = 0
while temp > 0:
sum += (temp % 10)
temp //=10
return sum
num = int(input('Enter a number to get its sum of digits: '))
digit_sum = Digitsum(num)
print('The sum of digits of {} is {}.'.format(num,digit_sum))
OUTPUT:
[Link] to find sum of two numbers using a user defined function with parameters.
CODE:
def sum_two(n1,n2):
Sum = n1 + n2
print('Sum of {} and {} is {}.'.format(n1,n2,Sum))
n1 = int(input('Enter the first number: '))
n2 = int(input('Enter the second number: '))
sum_two(n1,n2)
OUTPUT:
[Link] to find simple interest using a user defined function with parameters and with
return value.
CODE:
def simple_interest(principal, rate, time):
si = principal * rate * time/100
return si
p=int(input("Enter principal: "))
r=int(input("Enter rate: "))
t=int(input("Enter time: "))
s=simple_interest(p,r,t)
print("simple Interest= ",s)
OUTPUT:
[Link] to pass a list as function argument and modify it.
CODE:
def modify(list1,old,new):
for i in range(len(list1)):
if list1[i] == old:
list1[i] = new
print(list1)
list1 = ["CPU","Mouse","Keyboard","Graphic Card"]
modify(list1,"Keyboard","RGB-Keyboard")
OUTPUT:
[Link] to sort values in a list.
CODE:
n = int(input('Enter the number of items: '))
list1 = []
for i in range(n):
element = int(input('Enter the element: '))
[Link](element)
print('Unsorted list: ')
print(list1)
[Link]()
print('Sorted list: ')
print(list1)
OUTPUT:
[Link] to find minimum value in a list.
CODE:
l=[ int(l) for l in input("List:").split(",")]
print("The list is ",l)
min1 = l[0]
for i in range(len(l)):
if l[i] < min1:
min1 = l[i]
print("The smallest element in the list is: ",min1)
OUTPUT:
[Link] to check whether a value exists in dictionary.
CODE:
dict1 = {}
n = int(input('Enter the number of enteries: '))
for i in range(n):
key = input('Enter the key: ')
value = int(input('Enter the value associated with the key: '))
dict1[key] = value
x = int(input('Enter the value to check whether it is in the dictionary or not: '))
a = list([Link]())
b = list([Link]())
for i in range(len(a)):
if a[i]== x:
print('{} is associated with {} in the dictionary.'.format(x,b[i]))
break
else:
print('{} is not there in the values of ditionary.'.format(x))
OUTPUT:
[Link] to write rollno, name and marks of a student in a text file Marks.
CODE:
f = open('[Link]','w')
n = int(input('Enter the number of students: '))
for i in range(n):
name = input('Enter the name: ')
rollno = int(input('Enter the roll no.: '))
marks = int(input('Enter the marks: '))
list1 = [rollno, name, marks]
[Link](str(list1) + '\n')
[Link]()
OUTPUT:
[Link] to read and display contents of file [Link].
CODE:
f = open('[Link]', 'r')
data = [Link]()
print(data)
OUTPUT:
[Link] to read and display those lines from file that start with alphabet ‘T’.
CODE:
f = open('[Link]','r')
data = [Link]()
for line in data:
print(line,end='')
names = []
for i in range(len(data)):
name = ''
if len(str(i+1)) == 1:
for x in range(5,len(data[i])):
if data[i][x] == "'":
name += data[i][5:x]
break
elif len(str(i+1)) == 2:
for y in range(6,len(data[i])):
if data[i][y] == "'":
name += data[i][6:y]
break
[Link](name)
print('Names starting with \'t\' and their data:')
for t in range(len(names)):
if names[t][0].lower() == 't':
print(names[t])
for i in range(len(data)):
if names[t] in data[i]:
print(data[i],end='')
OUTPUT:
[Link] to read and display those lines from file that end with alphabet ‘n’.
CODE:
f = open('[Link]','r')
data = [Link]()
for line in data:
print(line,end='')
names = []
for i in range(len(data)):
name = ''
if len(str(i+1)) == 1:
for x in range(5,len(data[i])):
if data[i][x] == "'":
name += data[i][5:x]
break
elif len(str(i+1)) == 2:
for y in range(6,len(data[i])):
if data[i][y] == "'":
name += data[i][6:y]
break
[Link](name)
print('Names ending with \'n\' and their data:')
for t in range(len(names)):
if names[t][-1].lower() == 'n':
print(names[t])
for i in range(len(data)):
if names[t] in data[i]:
print(data[i],end='')
OUTPUT:
[Link] to count number of words in data file [Link].
CODE:
f = open('[Link]','r')
data = [Link]()
count = 0
#for x in
# [Link](str(x),'')
for line in data:
words = [Link](' ')
for word in words:
if word[-1] in '\':;.,/?"[]()!@#$%^&*{}|`~<>\-_+=':
word = word[0:-1]
count += 1
else:
count += 1
print('There are {} number of words in the file.'.format(count))
OUTPUT:
[Link] a python program to read a file named “[Link]”, count and print total
alphabets in the file?.
CODE:
f = open('[Link]','r')
data = [Link]()
count = 0
count_2 = 0
for i in range(len(data)):
if data[i].lower() in 'abcdefghijklmnopqrstuvwxyz':
count += 1
elif data[i] in ',.<>/?;:\'"[{]}\|-_=+)(*&^%$#@!`~':
count_2 += 1
print('Number of alphabets in the file are: {}'.format(count))
print('Number of punctuators in the file are: {}'.format(count_2))
OUTPUT:
[Link] to write data in a csv file [Link].
CODE:
import csv
f=open("[Link]","w",newline='')
s_writer=[Link](f)
s_writer.writerow(['RollNo','Name','Marks'])
rec=[]
while True:
r=int(input("Enter roll no: "))
n=input("Enter name: ")
m=int(input("Enter marks: "))
lst=[r,n,m]
[Link](lst)
ch=input("Do you want to enter more records?(y/n)")
if ch=='n':
break
for i in rec:
s_writer.writerow(i)
[Link]()
OUTPUT:
24. Program to read and display data from a csv file [Link].
CODE:
import csv
f = open("[Link]")
data = [Link](f)
for row in data:
print(row)
OUTPUT:
[Link] a python program to maintain book details like book code, book title and price
using stacks data
structures? (implement push(), pop() and traverse() functions)
CODE:
stack = []
while True:
choice = int(input('''Enter the number as per your choice:
--> 1. Pushing information about one book
--> 2. Popping the first item from the stack
--> 3. Peek the first element in the stack
--> 4. Returning the whole stack
--> 5. Returning each element of the stack
--> 0. Exit the loop
'''))
if choice == 1:
code = int(input('Enter the book code: '))
title = input('Enter the book title: ')
price = int(input('Enter the book price: '))
[Link]([code,title,price])
print('Credentials entered are pushed in the stack.')
elif choice == 2:
if len(stack) == 0:
print('The stack is empty.')
else:
pop_item = [Link]()
print(pop_item)
print('Returned the popped item.')
elif choice == 3:
if len(stack) == 0:
print('The stack is empty.')
else:
peek_item = [Link]()
print(peek_item)
print('Returned the first item.')
elif choice == 4:
if len(stack) == 0:
print('The stack is empty.')
else:
print(stack)
print('Returning the whole stack.')
elif choice == 5:
if len(stack) == 0:
print('The stack is empty.')
else:
print('Returning stack element by element:')
for i in stack:
print(i)
elif choice == 0:
break
print('You have exitted the loop.')
else:
print('Invalid choice.')
OUTPUT:
[Link] a python program to maintain employee details like empno,name and salary
using stacks data
structure? (implement insert(), delete() and traverse() functions)
CODE:
stack = []
while True:
choice = int(input('''Enter the number as per your choice:
--> 1. Pushing information about one employee
--> 2. Popping the first employee from the stack
--> 3. Peek the first employee in the stack
--> 4. Returning the whole stack of employees
--> 5. Returning each element of the stack
--> 0. Exit the loop
'''))
if choice == 1:
empno = int(input('Enter the employee number: '))
name = input('Enter the employee name: ') salary
= int(input('Enter the employee salary: '))
[Link]([empno,name,salary])
print('Credentials entered are pushed in the stack.')
elif choice == 2:
if len(stack) == 0:
print('The stack is empty.')
else:
pop_item = [Link]()
print(pop_item)
print('Returned the popped item.')
elif choice == 3:
if len(stack) == 0:
print('The stack is empty.')
else:
peek_item = [Link]()
print(peek_item)
print('Returned the first employee in the stack.')
elif choice == 4:
if len(stack) == 0:
print('The stack is empty.')
else:
print(stack)
print('Returning the whole stack.')
elif choice == 5:
if len(stack) == 0:
print('The stack is empty.')
else:
print('Returning stack element by element:')
for i in stack:
print(i)
elif choice == 0:
break
print('You have exitted the loop.')
else:
print('Invalid choice.')
OUTPUT:
[Link] a python program to read a file named “[Link]”, count and print the following:
(i) length of the file(total characters in file) (ii)total
alphabets
(iii) total upper case alphabets (iv) total
lower case alphabets (v) total digits
(vi) total spaces
(vii) total special characters
CODE: article_file=open("[Link]", "r+")
text=article_file.read()
count=0 space=0 upper=0
lower=0 digits=0
special_char=0 alphabets=0
for i in text:
if [Link]():
alphabets += 1 if [Link]():
upper += 1
if [Link]():
lower += 1 elif [Link]():
digits += 1
elif [Link]():
space += 1 else:
special_char += 1 for i in text:
if i != "":
count += 1 article_file.close()
print(f"Total Characters: {count}\nSpaces: {space}\nAlphabets: {alphabets}\nUppercase Characters:
{upper}\nLowercase Characters: {lower}\nDigits: {digits}\nSpecial Characters: {special_char}")
OUTPUT:
[Link] a python program to read a file named “[Link]”, count and print total words starting
with “a” or “A” in the file?
CODE:
f = open("[Link]","r")
lines = [Link]()
words =
[Link]()
print(words)
count = 0
for j in words:
if words[0] == 'a' or 'A':
count +=
1 print(count)
OUTPUT: