INSTITUTE OF INFORMATION TECHNOLOGY & MANAGEMENT
BACHELOR OF COMPUTER ADMINSTRATION (BCA)
Guru Gobind Singh Indraprastha University, Delhi
SUBMITTED TO: - SUBMITTED BY:
Ms.Madhumita Debnat Name: AMAN YADAV
Enrollment no:02921102021
Course: BCA-III E
Institute of Information & Management,
New Delhi-110058
Bach (2021-2024)
List of Practicals
S.NO Problem Statement Mapping to CO#
1 Write a program to enter two integers, two floating numbers and then CO1
perform all arithmetic operations on them.
2 Write a program to check whether a number is an Armstrong number or not. CO1
Write a python program to that accepts length of three sides of a triangle as
inputs. The program should indicate whether or not the triangle is a right
angled triangle (use Pythagorean theorem).
3 Write a python program to find factorial of a number using recursion. CO2
4 Write a program to print the sum of all the primes between two ranges. CO1
5 Write a python program to construct the following pattern using nested for CO2
loop:
*
**
***
****
*****
6 Write a program to swap two strings. CO1
7 Write a Program to Count the Occurrences of Each Word in a Given String CO2,CO3
Sentence.
8 Write a program to create, concatenate and print a string and accessing CO2
substring from a given string.
9 Write a menu driven program to accept two strings from the user and CO1,CO2
perform the various functions using user defined functions.
10 Write a program to find smallest and largest number in a list. CO2,CO3
11 Write a Program to Remove the ith Occurrence of the Given Word in a List. C02,CO3
12 Create a dictionary whose keys are month names and whose values are the CO2,CO3
number of days in the corresponding months.
Ask the user to enter a month name and use the dictionary to tell them how
many
days are in the month.
Print out all keys in the alphabetically order
Print out all the months with 31 days
Print out the key value pairs sorted by number of days in each month
13 Make a list of first 10 letters of the alphabet, then use the slicing to do the CO2,CO3
following operations:
Print the first 3 letters of the list
Print any 3 letters from the middle
Print the letter from any particular index to the end of the list
14 Write a program that scans an email address and forms a tuple of user name CO2,CO3
and domain.
15 Write a program that uses a user defined function that accepts name and CO2,CO3
gender (as M for Male, F for Female) and prefixes Mr./Ms. on the basis of
the gender.
16 Write a Program to Sort a List of Tuples in Increasing Order by the Last CO2,CO3
Element in Each Tuple.
17 Write a Program to Swap the First and Last Element in a List. CO2,CO3
18 Write a program to display Bar graphs or Pie chart using Matplotlib. CO2,CO3
19 Write a program that defines a function large in a module which will be used CO2,CO3
to find larger of two values and called from code in another module.
20 Write a python program to define a module to find Fibonacci Numbers and CO2,CO3
import the module to another program.
21 Write a program to know the cursor position and print the text according to CO2,CO3
specifications given below:
● Print the initial position
● Move the cursor to 4th position
● Display next 5 characters
● Move the cursor to the next 10 characters
● Print the current cursor position
● Print next 10 characters from the current cursor position
22 Create a binary file with roll number, name and marks. Input a roll number CO4
and perform the following operations:
update the marks.
Delete the record
Display the record
Append the record
Search the record
23 Write a program to Create a CSV file by entering user-id and password, read CO5
and search the password for given user id.
24 Write a Program to Count the Number of Words in a Text File. CO5
25 Write a Program to Count the Number of Lines in Text File. CO5
26 Write a program that inputs a text file. The program should print all of the CO4
unique words in the file in alphabetical order.
27 Write a Python class to implement pow(x, n). CO4
28 Write a program to create a numpy array. CO5
29 Write a program to Extract first n columns of a Numpy matrix. CO5
30 Write a program to sum all elements in a NumPy array. CO5
31 Write a program to add a list to a NumPy array . CO4,CO5
32 Write a program of Numpy convert 1-D array with 8 elements into a 2-D CO4,CO5
array in Python
Program -1 Write a program to enter two integers, two floating numbers and then perform all
arithmetic operations on them.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Addition: ",num1 + num2)
print("Subtraction: ",num1 - num2)
print("Multiplication: ",num1 * num2)
print("Division: ",num1 / num2)
print("Floor Division: ",num1 // num2)
print("Modulus: ", num1 % num2)
print("Exponentiation: ",num1 ** num2)
output
Program -2 Write a program to check whether a number is an Armstrong number or not
Code- num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
output
Program-3 Write a python program to that accepts length of three sides of a triangle as inputs.
The program should indicate whether or not the triangle is a right angled triangle (use
Pythagorean theorem).
Code- a = int(input("Enter first side : "))
b = int(input("Enter second side : "))
c = int(input("Enter third side : "))
if a + b > c and b + c > a and a + c > b :
print("Triangle Possible")
else :
print("Triangle Not Possible")
output
program 4 Write a python program to find factorial of a number using recursion
code- def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
output
program-5 Write a program to print the sum of all the primes between two ranges
code - lower_value = int(input ("Please, Enter the Lowest Range Value: "))
upper_value = int(input ("Please, Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ")
for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)
output-
program 6- Write a python program to construct the following pattern using nested for loop:
**
***
****
*****
Code- for i in range(10):
print(str(i) * i)
output
program-7 Write a program to swap two strings.
code- print("Enter the First String: ", end="")
string1 = input()
print("Enter the Second String: ", end="")
string2 = input()
print("\nString before swap:")
print("string1 =", string1)
print("string2 =", string2)
temp = string1
string1 = string2
string2 = temp
print("\nString after swap:")
print("string1 =", string1)
print("string2 =", string2)
output--
program-7 Write a Program to Count the Occurrences of Each Word in a Given String Sentence
code- string = "I am programmer. I am student."
word = "am"
words = string.split()
count = 0
for w in words:
if w == word:
count += 1
print(count)
output
program -8 Write a program to create, concatenate and print a string and accessing substring
from a given string.
code - print("Enter the First String: ")
strOne = input()
print("Enter the Second String: ")
strTwo = input()
strThree = strOne + strTwo
print("\nConcatenated String: ", strThree)
output -
program-9 Write a menu driven program to accept two strings from the user and perform the
various functions using user defined functions
program 10- Write a program to find smallest and largest number in a list
code lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :",
min(lst))
output
Program 11 Write a Program to Remove the ith Occurrence of the Given Word in a List
Code a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
print(a)
c=[]
count=0
b=input("Enter word to remove: ")
n=int(input("Enter the occurrence to remove: "))
for i in a:
if(i==b):
count=count+1
if(count!=n):
c.append(i)
else:
c.append(i)
if(count==0):
print("Item not found ")
else:
print("The number of repetitions is: ",count)
print("Updated list is: ",c)
print("The distinct elements are: ",set(a))
output
program 12 Create a dictionary whose keys are month names and whose values are the number
of days in the corresponding months.
Ask the user to enter a month name and use the dictionary to tell them how many
days are in the month.
Print out all keys in the alphabetically order
Print out all the months with 31 days
Print out the key value pairs sorted by number of days in each month
Code month = { "jan" : 31 , "feb" : 28 , "march" : 31 , "april" : 30 , "may" : 31 , "june" : 30 ,
"july" : 31 , "aug" : 31 , "sept" : 30 , "oct" : 31 , "nov" : 30 , "dec" : 31}
mon = input("Enter the month name in short form :- ")
print("Number of days in ",mon,"=",month [ mon ])
(ii)
month = { "jan" : 31 , "feb" : 28 , "march" : 31 , "april" : 30 , "may" : 31 , "june" : 30 , "july" : 31
, "aug" : 31 , "sept" : 30 , "oct" : 31 , "nov" : 30 , "dec" : 31}
lst = list ( month . keys() )
lst.sort()
print( lst )
(iii)
month = { "jan" : 31 , "feb" : 28 , "march" : 31 , "april" : 30 , "may" : 31 , "june" : 30 , "july" : 31
, "aug" : 31 , "sept" : 30 , "oct" : 31 , "nov" : 30 , "dec" : 31}
print( "Month which have 31 days !!-- ")
for i in month :
if month [ i ] == 31 :
print( i )
(iv)
month = { "jan" : 31 , "feb" : 28 , "march" : 31 , "april" : 30 , "may" : 31 , "june" : 30 , "july" : 31
, "aug" : 31 , "sept" : 30 , "oct" : 31 , "nov" : 30 , "dec" : 31}
print("Month according to number of days ---")
print("feb")
for i in month :
if month [ i ] == 30 :
print(i)
for i in month :
if month [ i ] == 31 :
print( i)
output
program 13 Make a list of first 10 letters of the alphabet, then use the slicing to do the following
operations:
Print the first 3 letters of the list
Print any 3 letters from the middle
Print the letter from any particular index to the end of the list
Code import string
# initializing empty list
test_list = []
# using string for filling alphabets
test_list = list(string.ascii_uppercase)
# printing resultant list
print ("List after insertion : " + str(test_list))
output
program 14 – Write a program that scans an email address and forms a tuple of user name and
domain.
code - test_str = 'manjeet@geeksforgeeks.com'
# printing original string
print("The original string is : " + str(test_str))
# slicing domain name using slicing
res = test_str[test_str.index('@') + 1 : ]
# printing result
print("The extracted domain name : " + str(res))
output
program -15 Write a program that uses a user defined function that accepts name and gender (as
M for Male, F for Female) and prefixes Mr./Ms. on the basis of the gender.
Code
def prefix(name,gender):
if (gender == 'M' or gender == 'm'):
print("Hello, Mr.",name)
elif (gender == 'F' or gender == 'f'):
print("Hello, Ms.",name)
else:
print("Please enter only M or F in gender")
name = input("Enter your name: "
gender = input("Enter your gender: M for Male, and F for Female: ")
prefix(name,gender)
output
program-16- Write a Program to Sort a List of Tuples in Increasing Order by the Last Element in
Each Tuple
code- def sort_tuple(my_tup):
my_len = len(my_tup)
for i in range(0, my_len):
for j in range(0, my_len-i-1):
if (my_tup[j][-1] > my_tup[j + 1][-1]):
temp = my_tup[j]
my_tup[j]= my_tup[j + 1]
my_tup[j + 1]= temp
return my_tup
my_tuple =[(1, 92), (34, 25), (67, 89)]
print("The tuple is :")
print(my_tuple)
print("The sorted list of tuples are : ")
print(sort_tuple(my_tuple))
output
program 17- Write a Program to Swap the First and Last Element in a List.
Code- def list_swapping(my_list):
size_of_list = len(my_list)
temp = my_list[0]
my_list[0] = my_list[size_of_list - 1]
my_list[size_of_list - 1] = temp
return my_list
my_list = [34, 21, 56, 78, 93, 20, 11, 9]
print("The list is :")
print(my_list)
print("The function to swap the first and last elements is swapped")
print(list_swapping(my_list))
output
program 18- Write a program to display Bar graphs or Pie chart using Matplotlib ?
code import numpy as np
import matplotlib.pyplot as plt
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30,
'Python':35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(courses, values, color ='maroon',
width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()
ouput -
program- 19 Write a program that defines a function large in a module which will be used to find
larger of two values and called from code in another module.
Code # Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
output
program 20 Write a python program to define a module to find Fibonacci Numbers and import
the module to another program.
code
def Fibonacci(n):
if n < 0:
print("Incorrect input")
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
output
program 21
program 22 Create a binary file with roll number, name and marks. Input a roll number and
perform the following operations:
update the marks.
Delete the record
Display the record
Append the record
Search the record
Code class Student:
marks = []
def getData(self, rn, name, m1, m2, m3):
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
print ("Roll Number is: ", Student.rn)
print ("Name is: ", Student.name)
#print ("Marks in subject 1: ", Student.marks[0])
#print ("Marks in subject 2: ", Student.marks[1])
#print ("Marks in subject 3: ", Student.marks[2])
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
print ("Average Marks are: ", self.average())
def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])
def average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)
r = int (input("Enter the roll number: "))
name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))
s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()
output
program 23 Write a program to Create a CSV file by entering user-id and password, read and
search the password for given user id.
code # Python program to demonstrate
# writing to CSV
import csv
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
# name of csv file
filename = "university_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
output
program 24 Write a Program to Count the Number of Words in a Text File.
Code # creating variable to store the
# number of words
number_of_words = 0
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt','r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = file.read()
# Splitting the data into separate lines
# using the split() function
lines = data.split()
# Adding the length of the
# lines in our number_of_words
# variable
number_of_words += len(lines)
# Printing total number of words
print(number_of_words)
output
program 25 Write a Program to Count the Number of Lines in Text File.
Code with open(r"myfile.txt", 'r') as fp:
lines = len(fp.readlines())
print('Total Number of lines:', lines)
output
program 26
code filename = input('Enter the name of the given file : ')
# In read mode, open the given file with the name 'filename'
with open(filename, 'r') as file:
# Using for loop, go over the lines in the sample file.
for line in file:
# Split the line into words using the split() function.
words = line.split()
# Traverse through the words using for loop.
for i in words:
# Traverse through all the characters of the word using another for loop.
for letter in i:
# Check to see if the letter is a digit, and if so, print it.
if(letter.isdigit()):
print(letter)
output
program 27 Write a Python class to implement pow(x, n).
code class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
print(py_solution().pow(2, -3));
print(py_solution().pow(3, 5));
print(py_solution().pow(100, 0));
output
program 28 Write a Python class to implement pow(x, n).
code import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
output
program 29 Write a program to Extract first n columns of a Numpy matrix.
Code import numpy as np
the_arr = np.array([[0, 1, 2, 3, 5, 6, 7, 8],
[4, 5, 6, 7, 5, 3, 2, 5],
[8, 9, 10, 11, 4, 5, 3, 5]])
print(the_arr[:, 1:5])
output
Program 30 Write a program to sum all elements in a NumPy array.
Code import numpy as np
array1 = np.array(
[[1, 2],
[3, 4],
[5, 6]])
total = np.sum(array1)
print(f'Sum of all the elements is {total}')
output
Program 31 Write a program to add a list to a NumPy array .
Code # importing library
import numpy
# initializing list
lst = [1, 7, 0, 6, 2, 5, 6]
# converting list to array
arr = numpy.array(lst)
# displaying list
print ("List: ", lst)
# displaying array
print ("Array: ", arr)
output
Program 32 Write a program of Numpy convert 1-D array with 8 elements into a 2-D array in
Python
Code # importing library
import numpy
# initializing list
lst = [1, 7, 0, 6, 2, 5, 6]
# converting list to array
arr = numpy.array(lst)
# displaying list
print ("List: ", lst)
# displaying array
print ("Array: ", arr)
output