Python Programming Lab Manual 3rd sem BCA
Python Programming Lab Manual 3rd sem BCA
Python Programming Lab Manual 3rd sem BCA
RAMAIAH FOUNDATION
No.11, 6th Main, Pipeline Road, MSRIT Post, M.S. Ramaiah Nagar, Bangalore-560054.
PYTHON PROGRAMMING
LAB MANUAL
CA-C15L
BCA III SEMISTER
NEP SYALLABUS
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))
print(d)
print(type(d))
print(e)
print(type(e))
print(f)
print(type(f))
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'>
<class 'list'>
<class 'tuple'>
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.
list=['Python','CN','OS','CA']
print(list)
#to insert a new item to the list without replacing any of the existing values
list.insert(2, 'SQL')
list.remove('CN')
list.append('BCA')
x=list.pop(0)
print("popped element=",x)
print(list)
list.clear()
print(list)
Output:
[]
In the above code, we have created a list my list with elements [1, 2, 3, 4, 5].
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.
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)
print(16 in tuple1)
print(tuple1[4])
Output:
(16, 4, 1976)
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.
a)print the dictionary items b)access items c)use get() d)change values e)use len()
#creating dictonary
print(dict)
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)
dict[2] = "SQL"
print(len(dict))
Output:
Updated Dictionary:
OS
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.
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
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
choice=1
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))
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:
Output:
1. To perform Addition
2. To perform Subtraction
3. To perform Multiplication
4. To perform Division
0. To Exit
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.
choice=1
while(choice!=0):
a=int(input())
if a>0:
else:
choice=int(input())
output:
-5
-5 is negative number
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)
output:
Explanation:
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()
new_date=today + datetime.timedelta(days=days_to_add)
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:
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)
Output:
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.
def count_characters(filename):
contents = file.read()
char_count = {}
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 char_count
file.write(data)
result = count_characters(filename)
Output:
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.
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)
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]]
(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
13. Write a python program to concatenate the data frames with two different objects
import pandas as pd
df1=pd.DataFrame({'Name':['Tommy','Fury'],'age':[20,21]},index=[1,2])
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:
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
df = pd.read_csv("https://people.sc.fsu.edu/~jburkardt/data/csv/hw_200.csv")
print(df.head(5))
print(df.tail(5))
Output:
First 5 Rows:
0 1 65.78 112.99
1 2 71.52 136.49
2 3 69.40 153.03
4 5 67.79 144.30
Last 5 Rows:
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
area=d.pi*r*r
Output:
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.