M.S.
RAMAIAH FOUNDATION
RAMAIAH INSTITUTE OF BUSINESS STUDIES (RIBS)
[Affiliated to Bangalore University & Recognized by Govt. of Karnataka]
No.11, 6th Main, Pipeline Road, MSRIT Post, M.S. Ramaiah Nagar, Bangalore-560054.
Phone:080-23607643/41 Telefax:080-23607642 Office:080-23607643.
PYTHON PROGRAMMING
LAB MANUAL
CA-C15L
BCA III SEMISTER
NEP SYALLABUS
Department of BCA, RIBS 1
1. Write a program to demonstrate basic data types in python
a = 20 #int
print(a)
print(type(a))
b = 20.5 #float
print(b)
print(type(b))
c = 1j #complex
print(c)
print(type(c))
d = "hello world" #String
print(d)
print(type(d))
e = ["Python", "OS", "CN"] #list
print(e)
print(type(e))
f = ("Python", "CN", "OS") #tuple
print(f)
print(type(f))
Department of BCA, RIBS 2
g = {"name" : "anu", "age" : 36} #dict
print(g)
print(type(g))
h = True #bool
print(h)
print(type(h))
i = b"Hello" #bytes
print(i)
print(type(i))
Output:
20
<class 'int'>
20.5
<class 'float'>
1j
<class 'complex'>
hello world
<class 'str'>
['Python', 'OS', 'CN']
<class 'list'>
('Python', 'CN', 'OS')
<class 'tuple'>
{'name': 'anu', 'age': 36}
Department of BCA, RIBS 3
<class 'dict'>
True
<class 'bool'>
b'Hello'
<class 'bytes'>
Explanation:
In the above code, we have declared variables with different data types in Python and printed
their type and value.
'a' is an integer type with value 10
'b' is a float type with value 20.5 .
'c' is a string type with value "Python"
'd' is a boolean type with value True
'e' is a list type with values [1, 2, 3, 4]
.'f' is a tuple type with values (1, 2, 3, 4)
'g' is a dictionary type with values ("name": "Srikanth", "age": 30)
‘h’ is a Boolean type with values True or False
‘I’ returns the type byte
2. Create a list and perform the following methods
a) Insert b) remove c) append d) len e) pop f) clear
list=['Python','CN','OS','CA']
print("Elements of the list, my list are:")
print(list)
#to insert a new item to the list without replacing any of the existing values
list.insert(2, 'SQL')
print("inserting SQL at index 2 :",list)
Department of BCA, RIBS 4
#removes the specified data item from the list
list.remove('CN')
print("removing computer networks from list ", list)
#append is used to add the item at the end of the list
list.append('BCA')
print("appending BCA to the list",list)
#length specifies the number of data items present in the list
print("length of the items in the list ",len(list))
#removes the data item present at the specified index
x=list.pop(0)
print("popped element=",x)
print(list)
#empties the content of the list
list.clear()
print(list)
Output:
Elements of the list, my list are:
['Python', 'CN', 'OS', 'CA']
inserting SQL at index 2 : ['Python', 'CN', 'SQL', 'OS', 'CA']
removing computer networks from list ['Python', 'SQL', 'OS', 'CA']
appending BCA to the list ['Python', 'SQL', 'OS', 'CA', 'BCA']
length of the items in the list 5
popped element= Python
['SQL', 'OS', 'CA', 'BCA']
[]
Department of BCA, RIBS 5
Explanation:
In the above code, we have created a list my list with elements [1, 2, 3, 4, 5].
We perform the following operations on the list:
The insert() method is used to insert an element at a specific index. In this case, we have
inserted 10 at index 2.
The remove() method is used to remove an element from the list. In this case, we have
removed 5 from the list.
The append() method is used to append an element to the end of the list. In this case, we
have appended 20 to the end of the list.
The len() function is used to get the length of the list. The pop() method is used to
remove the last element from the list.
The clear() method is used to remove all elements from the list.
3.Create a tuple and perform the following methods
a) additems() b)length c)c heck for the items in tuple d) access items
tuple=(16,4,1976)
print(tuple)
#add items
tuple1=tuple +(1,8,2008)
print(tuple1)
#to find number of items in tuple
print("length of the tuple=",len(tuple1))
#to check for item in tuple
print(16 in tuple1)
#accessing item in the tuple at index 4
print(tuple1[4])
Output:
(16, 4, 1976)
(16, 4, 1976, 1, 8, 2008)
Department of BCA, RIBS 6
length of the tuple= 6
True
Explanation:
In the above code, we have created a tuple my tuple with elements (1, 2, 3, 4, 5). We perform the
following operations on the tuple:
The len() function is used to get the length of the tuple. . The in operator is used to check
if an item exists in the tuple. In this case, we check if 2 exists in the tuple.
Tuples are ordered, and we can access elements in a tuple using indices. In this case, we
access the element at index 2 in the tuple.
Since tuples are immutable, we can't add elements to them directly. To add elements to a tuple,
we first convert the tuple to a list using the list() function. Then, we can use the insert() method
to insert an element at a specific index and the append() method to add an element to the end of
the list. Finally, we convert the list back to a tuple using the tuple() function. The updated tuple
is printed with the print() statement.
4. Create a dictionary and apply the following methods
a)print the dictionary items b)access items c)use get() d)change values e)use len()
#creating dictonary
dict = {1:"Python",2: "CN",3:"OS"}
print(dict)
#adding elements to dictonary
dict["4"] = "CA"
print("Updated Dictionary:\n",dict)
#The get() method returns the value of the item with the specified key.
x = dict.get(3)
print(x)
#changing values in dictonary
dict[2] = "SQL"
Department of BCA, RIBS 7
print(dict)
#finding number of items i.e key value pairs present in dictonary
print(len(dict))
Output:
{1: 'Python', 2: 'CN', 3: 'OS'}
Updated Dictionary:
{1: 'Python', 2: 'CN', 3: 'OS', '4': 'CA'}
OS
{1: 'Python', 2: 'SQL', 3: 'OS', '4': 'CA'}
Explanation:
In the above code, we create a dictionary student with keys name, age, and grade and
corresponding values.
We print the items in the dictionary directly using the .items() method. • We use a for
loop to traverse the dictionary and print each item in the dictionary.
We access the values in the dictionary using both the square bracket notation and the get
method.
We change the value of grade key in the dictionary.
Finally, we find the length of the dictionary using the len() function.
5. Write a program to create a menu with following options
a. to perform addition
b. to perform subtraction
c. to perform multiplication
d. to perform division
accept user input and perform operations accordingly use function with arguments
Department of BCA, RIBS 8
def add(a,b):
x=(a+b)
return x
def sub(a,b):
x=(a-b)
return x
def mul(a,b):
x=(a*b)
return x
def div(a,b):
x=(a/b)
return x
print("program to perform Arithmetic operation \n")
choice=1
print("1. To perform Addition \n")
print("2. To perform Subtraction \n")
print("3. To perform Multiplication \n")
print("4. To perform Division \n")
print("0. To Exit\n")
while(choice!=0):
p=int(input("enter a number\n"))
q=int(input("enter a number\n"))
choice=int(input("enter a choice\n"))
if(choice==1):
print("addition =",add(p,q))
Department of BCA, RIBS 9
elif(choice==2):
print("subtraction =",sub(p,q))
elif(choice==3):
print("multiplication =",mul(p,q))
elif(choice==4):
print("division =",div(p,q))
elif(choice==0):
break
else:
print("Invalid option ")
Output:
program to perform Arithmetic operation
1. To perform Addition
2. To perform Subtraction
3. To perform Multiplication
4. To perform Division
0. To Exit
enter a number
Department of BCA, RIBS 10
enter a number
enter a choice
multiplication = 2
Explanation:
The program is a simple calculator which performs basic arithmetic operations (addition,
subtraction, multiplication, division). It offers the user a menu of options to choose from and
then accepts the inputs. The program uses functions for each operation with arguments and calls
the respective function based on the user's choice. It continues until the user presses option 0 to
exit. If the user enters an invalid option, it displays an error message.
6. Write a program to print a number is positive/negative using IF-ELSE
print("program to check positive or negative ")
choice=1
while(choice!=0):
print("enter a number ")
a=int(input())
if a>0:
print(a,"is positive number ")
else:
print(a,"is negative number")
print("Enter 1 to continue and 0 to exit ")
choice=int(input())
output:
program to check positive orr negative
Department of BCA, RIBS 11
enter a number
-5
-5 is negative number
Enter 1 to continue and 0 to exit
Explanation:
The input method is used to accept input from the user in the form of a string
The int() is used to convert the string to an integer.
if checks if the number is greater than or equal to zero, and if so, it prints "is a positive
number". Else executes if the number is less than zero and prints "is a negative number".
7. Write a program for filter() to filter only even numbers from a given list
def even(x):
return x % 2 == 0
a = [1,2,3,4,5,10,13,16]
result = filter(even,a)
print('orginal list:',a)
print('Filtered list :',list(result))
output:
orginal list: [1, 2, 3, 4, 5, 10, 13, 16]
Filtered list : [2, 4, 10, 16]
Explanation:
The variable 'a' is a list of integers.
The even() function takes an integer as an argument and returns True if it is even, and
False if it is odd.
The filter() method takes two arguments, the first is a function and the second is an
iterable (in this case, the list numbers). It filters out elements from the list that return
False when passed to the function.
Department of BCA, RIBS 12
We have a list of numeric values. And we have a function even_numbers() which returns
True if a number passed as a parameter is an even number otherwise returns False.
Wewill be using the filter() function to list down all the even numbers in the given list
8.Write a program to print date,time for today and now
import datetime
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
output:
2023-02-03 15:23:05.803920
2023-02-03 15:23:05.803919
Explanation:
The import datetime imports the datetime module, which provides classes to work with
dates and times.
The statement datetime.datetime.now returns the current date and time as a datetime
object.
The print() function is used to print the current date and time, which is stored in the
variable now.
9. Write a python program to add some days to your present date and print the date added
import datetime
today = datetime.datetime.now().date()
print("current date is",today)
days_to_add = int(input("Enter the number of days to add : "))
new_date=today + datetime.timedelta(days=days_to_add)
print("date after adding",days_to_add, " days is :", new_date)
Department of BCA, RIBS 13
Output:
current date is 22/12/22
after adding days
2022-12-27 00:00:00
Explanation:
This code calculates and prints the date after adding a specified number of days to the
current date. Here's a more detailed explanation of each step:
Importing the datetime module: The first line of the code imports the datetime module
from the Python Standard Library. This module provides classes for working with dates
and times
Getting the current date: The line today = datetime.datetime.now().date() gets the current
date as a date object using the now() method from the datetime class. The date() method
is then called on the datetime object to extract only the date component. The result is
stored in the today variable.
Printing the current date: The line print("Current Date is :", today) prints the current date
stored in the today variable.
Entering the number of days to add: The line days_to_add = int(input("Enter the number
of days to add :")) prompts the user to enter the number of days to add. The input()
function returns the entered value as a string, which is then converted to an integer using
the int () function and stored in the days to add variable.
Calculating the new date: The line new date today+ datetime.timedelta(days days to add)
calculates the new date by creating a timedelta object that represents days to add days
using the timedelta class from the datetime module. The timedelta object is then added to
the today variable to get the new date, which is stored in the new_date variable.
Printing the new date: The line print("Date after adding ", days_to_add, "days is", new
date) prints the new date stored in the new date_variable.
10. Write a program to count number of characters in a given string and store them in a
dictionary data structure
str=input("Enter a String:")
dict = {}
for n in str:
Department of BCA, RIBS 14
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)
Output:
Enter a String: hello
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
Explanation:
The count characters function takes a string as input and returns a dictionary that maps each
character in the string to its count. The function creates an empty dictionary char_count, loops
through each character in the string, and either increments the count of the character if it's
already in the dictionary, or adds the character to the dictionary and sets its count to 1 if it's not.
Finally, the function returns the char_count dictionary.
11. Write a python program to count frequency of characters in a given file
def count_characters(filename):
#Open the file in read mode
with open(filename,"r") as file:
#Read the contents of the file into a string
contents = file.read()
# Create an empty dictionary
char_count = {}
#Loop through each character in the string
Department of BCA, RIBS 15
for char in contents:
# If the character is already in the dictionary, increment its count by 1
if char in char_count:
char_count[char] += 1
# If the character is not in the dictionary, add it and set its count to 1
else:
char_count [char] = 1
# Return the dictionary
return char_count
# Input the data
data = input("Enter the data: ")
# Input the filename to be saved
filename = input("Enter the filename to save the data: ")
#Write the data to the file
with open(filename, "w") as file:
file.write(data)
#Inform that the file is being opened for reading
print("Opening the file '" + filename + " for reading...")
# Call the function and store the result in a variable
result = count_characters(filename)
# Print the result
print("Character frequency in " + filename + " is : \n" + str(result))
Output:
Enter the data: python
Enter the filename to save the data: file.txt
Department of BCA, RIBS 16
Opening the file 'file.txt for reading...
Character frequency in file.txt is :
{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}
Explanation:
The given program counts the frequency of characters in a file. It starts by asking the user
to enter the data that needs to be stored in the file. The user is then prompted to enter the
name of the file where the data needs to be saved. The data is then stored in the file using
the write method of the file object.
Once the data is stored in the file, the program informs the user that it is opening the file
for reading and calls the count characters function. This function takes the filename as an
argument and opens the file in read mode using the open method. The contents of the file
are then read into a string using the read method. The function then creates an empty
dictionary and loops through each character in the string. If a character is already in the
dictionary, its count is incremented by 1. If the character is not in the dictionary, it is
added and its count is set to 1. Finally, the function returns the dictionary which stores the
frequency of each character in the file. The result is then printed to the console.
12.Using numpy module create an array and check the following
1.Type of array 2.Axis of array 3.Shape of array 4.Type of elements in array
import numpy as np
arr=np.array([1,2,3,4,5])
print(arr)
print(type(arr))
nparray=np.array([[1,2,3],[11,22,33],[4,5,6],[8,9,10],[20,30,40]])
print(nparray)
output=nparray.sum(axis=1)
print("\n\nSum column-wise:",output)
arr=np.array([[1,2,3,4],[5,6,7,8]])
print(arr.shape)
Department of BCA, RIBS 17
arr=np.array([1,2,3,4])
print(arr.dtype)
Output:
[1 2 3 4 5]
<class 'numpy.ndarray'>
[[ 1 2 3]
[11 22 33]
[ 4 5 6]
[ 8 9 10]
[20 30 40]]
Sum column-wise: [ 6 66 15 27 90]
(2, 4)
int32
Explanation:
The given program is used to create an array using the NumPy module in Python and check
various attributes of the array. NumPy is a library for the Python programming language that is
used for scientific computing and data analysis. It provides functions for creating and
manipulating arrays, which are multi-dimensional collections of numerical data.
In the program, the first attribute that is checked is the "type of array." This refers to the class
of the object created by the NumPy np.array method. In this case, the type of the array will be
numpy.ndarray, which is the class that represents arrays in NumPy.
The next attribute checked is the "axes of array." The number of axes of an array refers to the
number of dimensions in the array. In NumPy, an array can have one or more axes, where each
axis represents a separate dimension. In this program, the number of axes is found using the
np.array function, which returns the number of dimensions of the input array. In general, when
the array has more than one dimension, it is called a multi-dimensional array and the number of
dimensions is equal to the number of axes.
The third attribute checked is the "shape of array." The shape of an array refers to the size of
the array along each of its axes. In this program, the shape of the array is found using the shape
Department of BCA, RIBS 18
attribute of the arr object. This returns a tuple that represents the size of the array along each of
its axes.
Finally, the "type of elements in array" is checked. This refers to the data type of the elements
stored in the array. In NumPy, arrays can contain elements of different data types, such as
integers, floats, or strings. In this program, the type of elements in the array is found using the
dtype attribute of the arr object. This returns the data type of the elements in the array. such as
int32 or float64.
13. Write a python program to concatenate the data frames with two different objects
import pandas as pd
#create a first Datafram
df1=pd.DataFrame({'Name':['Tommy','Fury'],'age':[20,21]},index=[1,2])
#create second Datafram
df2=pd.DataFrame({'Name':['Jake','Paul'],'age':[22,3]},index=[3,4])
print(pd.concat([df1,df2]))
Output:
Name age
1 Tommy 20
2 Fury 21
3 Jake 22
4 Paul 3
Explanation:
Meaning and Purpose of DataFrame in Pandas: A DataFrame is a 2-dimensional labeled data
structure with columns of potentially different types. It is a primary data structure in the Pandas
library, used for data manipulation and analysis. The purpose of a DataFrames to store and
manipulate tabular data, such as rows and columns,
Department of BCA, RIBS 19
The above program utilizes the Pandas library to demonstrate the creation and manipulation of
two DataFrames, dfl and df2. The pd.DataFrame() function is used to create each DataFrame,
with a dictionary of data passed as an argument.
Each DataFrame contains columns for names, age with the index specified for each
row.
The two DataFrames are then concatenated using the pd.concat() function, which
merges the two DataFrames into a single DataFrame, result.
The print function is used to display the resulting concatenated DataFrame.
In general, DataFrames are a crucial data structure in Pandas, used for storing and analyzing
tabular data with labeled rows and columns.
14. Write a python program to read a CSV file using pandas module and print the first and
last five lines of a file
import pandas as pd
# Read the csv file into a DataFrame using pd.read_csv()
df = pd.read_csv("https://people.sc.fsu.edu/~jburkardt/data/csv/hw_200.csv")
# Display the first 5 rows of the DataFrame using head()
print("First 5 Rows: ")
print(df.head(5))
# Display the last 5 rows of the DataFrame using tail()
print("\nLast 5 Rows: ")
print(df.tail(5))
Output:
First 5 Rows:
Index Height(Inches)" "Weight(Pounds)"
0 1 65.78 112.99
1 2 71.52 136.49
2 3 69.40 153.03
Department of BCA, RIBS 20
3 4 68.22 142.34
4 5 67.79 144.30
Last 5 Rows:
Index Height(Inches)" "Weight(Pounds)"
195 196 65.80 120.84
196 197 66.11 115.78
197 198 68.24 128.30
198 199 68.02 127.47
199 200 71.39 127.88
Explanation:
The above program uses the Pandas library to read a csv file located at
https://people.sc.fsu. edu/~jburkardt/data/csv/hw 200.csv. The pd.read_csv() function is
used to read the csv file into a Pandas DataFrame, which is a 2-dimensional labeled data
structure that is used to store and manipulate data in a tabular form.
This URL contains a csv file with data about human body weight, including the person's
index number, their weight in pounds, and their height in inches.
Once the csv file has been read into the DataFrame, the first 5 rows of the DataFrame are
displayed using the head() function and the last 5 rows of the DataFrame are displayed
using the tail function. These functions return a specified number of rows from the
beginning (head) or end (tail) of the DataFrame.
It is important to note that this program requires an internet connection in order to access
the csv file from the URL. If there is no internet connection, the user should create a local
csv file with 15 lines and use the following code to read the csv file into a DataFrame:
df = pd.read_csv("<local_csv_file_path>")
15. WAP which accepts the radius of a circle from user and compute the area( Use math
module)
import math as d
r=float(input("enter the radius of circle"))
area=d.pi*r*r
Department of BCA, RIBS 21
circle=2*d.pi*r
print("Area of circle is ",area)
print("circumference of circle is ",circle)
Output:
enter the radius of circle 10
Area of circle is 314.1592653589793
circumference of circle is 62.83185307179586
Explanitation:
The above program calculates the area of a circle given the radius. The user inputs the radius of
the circle, which is then used to calculate the area of the circle using the formula πr^2 i. e pi*r
square. The math module is imported to use the value of in the calculation. The user input is
received using the input function and is stored as a string. The string is then converted to a float
using the float() function, allowing the radius to be used in mathematical calculations The area of
the circle is calculated and stored in a variable, area. Finally, the value of area is printed to the
console.
Department of BCA, RIBS 22