The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Python Programming (Practical)
Programs List:
Part-A
1. Check if a number belongs to the Fibonacci Sequence.
2. Solve Quadratic Equations.
3. Find the sum of n natural numbers.
4. Display Multiplication Tables.
5. Check if a given number is a Prime Number or not
6. Implement a sequential search.
7. Create a calculator program.
8. Explore string functions.
9. Implement Selection Sort.
10. Implement Stack.
11. Read and write into a file.
Part-B
1. Demonstrate usage of basic regular expressions.
2. Demonstrate use of advanced regular expressions for data validation.
3. Demonstrate use of List.
4. Demonstrate use of Dictionaries.
5. Create SQLite Database and Perform Operations on Tables.
6. Create a GUI using the Tkinter module.
7. Demonstrate Exceptions in Python.
8. Drawing Line chart and Bar chart using Matplotlib.
9. Drawing Histogram and Pie chart using Matplotlib.
10. Create Array using NumPy and Perform Operations on Array.
11. Create DataFramefrom Excel sheet using Pandas and Perform Operations
on DataFrames
1 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Part A
1. Check if a number belongs to Fibonacci sequence
def fib(n):
if n <=0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
n = int(input("Enter the number of Fibonacci Series to generate: "))
f = [fib(i) for i in range(n)]
print(f"The first {n} numbers in the Fibonacci sequence are: {f}")
check = int(input("Enter the number to be searched: "))
if check in f:
print(f"The number {check} is a Fibonacci Number.")
else:
print("The entered number {check} is not a Fibonacci Number.")
Output
Enter the number of Fibonacci Series to generate: 10
The first 10 numbers in the Fibonacci sequence are: [0, 1, 1, 2, 3, 5, 8, 13, 21,
34]
Enter the number to be searched: 8
The number 8 is a Fibonacci Number.
Enter the number of Fibonacci Series to generate: 10
The first 10 numbers in the Fibonacci sequence are: [0, 1, 1, 2, 3, 5, 8, 13, 21,
34]
Enter the number to be searched: 6
The entered number is not a Fibonacci Number.
2 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
2. Solve Quadratic equations
print("Equation: ax^2 + bx + c ")
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
d=b**2-4*a*c
d1=d**0.5
if(d<0):
print("The roots are imaginary. ")
else:
r1=(-b+d1)/(2*a)
r2=(-b-d1)/(2*a)
print("The first root: ",round(r1,2))
print("The second root: ",round(r2,2))
Output
Equation: ax^2 + bx + c
Enter a: 1
Enter b: 2
Enter c: 3
The roots are imaginary.
Equation: ax^2 + bx + c
Enter a: 1
Enter b: 5
Enter c: 3
The first root: -0.7
The second root: -4.3
3 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
3. Find the sum of n natural number
n=int(input("Enter a number: "))
i=1
sum = 0
while( i <= n):
sum=sum+i
i=i+1
print("The sum of first n natural numbers is",sum)
(Or)
n=int(input("Enter a number: "))
sum = 0
while(n > 0):
sum=sum+n
n=n-1
print("The sum of first n natural numbers is",sum)
Output:
Enter a number: 8
The sum of first n natural numbers is 36
4 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
4. Display multiplication tables
num = int(input("Display multiplication table of? "))
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Output:
Display multiplication table of? 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
5 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
5. Check if a given number is prime or not
a=int(input("Enter number: "))
k=0
for i in range(2,a): ( or ) for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print("Number is prime")
else:
print("Number isn't prime")
Output:
Enter number: 7
Number is prime
Output:
Enter number: 20
Number isn't prime
6 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
6. Implement a sequential search
def sequence_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9, 12]
key = eval(input("Enter the element to find:"))
n = len(list1)
res = sequence_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Output:
Enter the element to find: 6
Element not found
Enter the element to find: 4
Element found at index: 3
7 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
7. Create a Calculator program
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# Function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
# Function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
# Function to divide two numbers
def divide(num1, num2):
return num1 / num2
print("Please select operation -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
# Take input from the user
select = int(input("Select operations form 1, 2, 3, 4 :"))
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
if select == 1:
8 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
print(number_1, "+", number_2, "=",
add(number_1, number_2))
elif select == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == 4:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input")
Output:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 :1
Enter first number: 2
Enter second number: 2
2+2=4
9 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
8. Explore String functions
text = 'PytHON PrograMMing'
# upper() function to convert
# string to upper case
print("\nUPPERCASE:")
print(text.upper())
# lower() function to convert
# string to lower case
print("\nLOWERCASE :")
print(text.lower())
# converts the first character to
# upper case and rest to lower case
print("\nSentence case")
print(text.title())
# swaps the case of all characters in the string
# upper case character to lowercase and viceversa
print("\nSwapcase")
print(text.swapcase())
# convert the first character of a string to uppercase
print("\nTitle")
print(text.capitalize())
# original string never changes
print("\nOriginal String")
print(text)
10 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Output:
UPPERCASE:
PYTHON PROGRAMMING
LOWERCASE :
python programming
Sentence case
Python Programming
Swapcase
pYThon pROGRAmmING
Title
Python programming
Original String
PytHON PrograMMing
11 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
9. Implement Selection Sort
def selection_sort(array):
length = len(array)
for i in range(length-1):
minIndex = i
for j in range(i+1, length):
if array[j]<array[minIndex]:
minIndex = j
array[i], array[minIndex] = array[minIndex], array[i]
return array
array = [21,6,9,33,3]
print("The sorted array is: ", selection_sort(array))
Output:
The sorted array is: [3, 6, 9, 21, 33]
12 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
10. Implement Stack
stack = []
# append() function to push element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
# pop() function to pop element from stack in LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
Output:
Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Stack after elements are popped:
[]
13 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
11. Read and write into a file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close()
file1 = open("myfile.txt", "r+")
print("Output of Read function is ")
print(file1.read())
print()
# byte from the beginning.
file1.seek(0)
print("Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
14 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
15 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Part B
1. Demonstrate usage of basic regular expressions.
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
x = re.split("\s", txt)
print(x)
x = re.sub("\s", "9", txt)
print(x)
x = re.search("ai", txt)
print(x) #this will print an object
Output
['ai', 'ai']
The first white-space character is located in position: 3
['The', 'rain', 'in', 'Spain']
The9rain9in9Spain
<re.Match object; span=(5, 7), match='ai'>
16 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
2. Demonstrate use of advanced regular expressions for data validation.
import re
# Email Validation
def validate_email(email):
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
return True
return False
# Password Validation
def validate_password(password):
pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-
z\d@$!%*?&]{8,}$"
if re.match(pattern, password):
return True
return False
# Phone Number Validation
def validate_phone_number(phone_number):
pattern = r"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"
if re.match(pattern, phone_number):
return True
return False
# Test the functions
email = "
[email protected]"
password = "Password123!"
phone_number = "(123) 456-7890"
print("Email Validation:", validate_email(email))
17 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
print("Password Validation:", validate_password(password))
print("Phone Number Validation:", validate_phone_number(phone_number))
Output
Email Validation: True
Password Validation: True
Phone Number Validation: True
18 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
3. Demonstrate use of List.
# Initialize a list
my_list = [10, 20, 30, 40, 50]
# Print the original list
print("Original List:", my_list)
# 1. Accessing elements
print("First element:", my_list[0])
print("Last element:", my_list[-1])
# 2. Slicing a list
print("Sliced List (2nd to 4th elements):", my_list[1:4])
# 3. Adding elements
my_list.append(60)
print("List after appending 60:", my_list)
my_list.insert(2, 25)
print("List after inserting 25 at index 2:", my_list)
# 4. Removing elements
my_list.remove(30)
print("List after removing 30:", my_list)
popped_element = my_list.pop() # Removes the last element
print("List after popping last element:", my_list)
print("Popped element:", popped_element)
del my_list[1] # Deletes the element at index 1
19 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
print("List after deleting element at index 1:", my_list)
# 5. Finding elements
index_of_40 = my_list.index(40)
print("Index of 40:", index_of_40)
count_of_40 = my_list.count(40)
print("Count of 40 in list:", count_of_40)
# 6. List concatenation
new_list = my_list + [70, 80, 90]
print("Concatenated List:", new_list)
# 7. Repeating elements
repeated_list = my_list * 2
print("Repeated List:", repeated_list)
# 8. Sorting a list
my_list.sort()
print("Sorted List:", my_list)
my_list.sort(reverse=True)
print("List sorted in descending order:", my_list)
# 9. Reversing a list
my_list.reverse()
print("Reversed List:", my_list)
# 10. Clearing the list
my_list.clear()
20 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
print("List after clearing all elements:", my_list)
Output
Original List: [10, 20, 30, 40, 50]
First element: 10
Last element: 50
Sliced List (2nd to 4th elements): [20, 30, 40]
List after appending 60: [10, 20, 30, 40, 50, 60]
List after inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]
List after removing 30: [10, 20, 25, 40, 50, 60]
List after popping last element: [10, 20, 25, 40, 50]
Popped element: 60
List after deleting element at index 1: [10, 25, 40, 50]
Index of 40: 2
Count of 40 in list: 1
Concatenated List: [10, 25, 40, 50, 70, 80, 90]
Repeated List: [10, 25, 40, 50, 10, 25, 40, 50]
Sorted List: [10, 25, 40, 50]
List sorted in descending order: [50, 40, 25, 10]
Reversed List: [10, 25, 40, 50]
List after clearing all elements: []
21 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
4. Demonstrate use of Dictionaries.
# Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Accessing values by keys
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
# Adding a new key-value pair
person["email"] = "
[email protected]"
print("\nAfter adding email:", person)
# Modifying an existing value
person["age"] = 31
print("\nAfter modifying age:", person)
# Removing a key-value pair using pop()
removed_value = person.pop("city")
print("\nAfter removing city:", person)
print("Removed value:", removed_value)
# Checking if a key exists in the dictionary
if "email" in person:
print("\nEmail exists in dictionary")
22 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
# Iterating over dictionary keys
print("\nIterating over keys:")
for key in person:
print(key)
# Iterating over dictionary values
print("\nIterating over values:")
for value in person.values():
print(value)
# Iterating over key-value pairs
print("\nIterating over key-value pairs:")
for key, value in person.items():
print(f"{key}: {value}")
# Clearing all elements from the dictionary
person.clear()
print("\nAfter clearing dictionary:", person)
Output
Name: Alice
Age: 30
City: New York
After adding email: {'name': 'Alice', 'age': 30, 'city': 'New York', 'email':
'[email protected]'}
After modifying age: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email':
'[email protected]'}
After removing city: {'name': 'Alice', 'age': 31, 'email': '[email protected]'}
23 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Removed value: New York
Email exists in dictionary
Iterating over keys:
name
age
email
Iterating over values:
Alice
31
[email protected]Iterating over key-value pairs:
name: Alice
age: 31
email:
[email protected]After clearing dictionary: {}
24 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
5. Create SQLite Database and perform operations on tables.
i) Creating database
import sqlite3
file = "RK.db"
try:
conn = sqlite3.connect(file)
print("Database RK formed.")
except:
print("Database Rk not formed.")
Output
ii) Connecting the Database:
import sqlite3
try:
# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect('RK.db')
cursor = sqliteConnection.cursor()
print('DB Init')
# Write a query and execute it with cursor
25 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
query = 'select sqlite_version();'
cursor.execute(query)
# Fetch and output result
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))
# Close the cursor
cursor.close()
# Handle errors
except sqlite3.Error as error:
print('Error occurred - ', error)
# Close DB Connection irrespective of success
# or failure
finally:
if sqliteConnection:
sqliteConnection.close()
print('SQLite Connection closed')
Output:
26 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
iii) Creating a table :
import sqlite3
connection_obj = sqlite3.connect('RK.db')
# cursor object
cursor_obj = connection_obj.cursor()
# Drop the GEEK table if already exists.
cursor_obj.execute("DROP TABLE IF EXISTS STUDENT")
# Creating table
table = """ CREATE TABLE STUDENT (
Email VARCHAR(255) NOT NULL,
First_NameCHAR(25) NOT NULL,
Last_NameCHAR(25),
Score INT
); """
cursor_obj.execute(table)
print("Table is Ready")
# Close the connection
connection_obj.close()
Output:
iv) Insert a row into a table & Display the table:
# Import module
import sqlite3
# Connecting to sqlite
27 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
conn = sqlite3.connect('RK.db')
# Creating a cursor object using the
# cursor() method
cursor = conn.cursor()
# Queries to INSERT records.
cursor.execute('''INSERT INTO STUDENT VALUES ('KAVYA','K','B',35)''')
# Display data inserted
print("Data Inserted in the table: ")
data=cursor.execute(''' select * from STUDENT''')
for row in data:
print(row)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
Output:
6. Create a GUI using the Tkinter module.
from tkinter import *
ws = Tk()
ws.geometry("300x300") #creating title
ws.title("Registration form")
l1=Label(ws,text="Registration form",width=20,font=("bold", 20))
l1.place(x=90,y=53)
#creating name text box
l2=Label(ws,text="Full Name",width=20,font=("bold", 10))
28 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
l2.place(x=80,y=130)
name=Entry(ws)
name.place(x=240,y=130) #creating email id text box
labl_2 = Label(ws, text="Email",width=20,font=("bold", 10))
labl_2.place(x=68,y=180)
entry_02 = Entry(ws)
entry_02.place(x=240,y=180)
#creating a checkbox for gender var1=IntVar()
labl_3 = Label(ws, text="Gender",width=20,font=("bold", 10))
labl_3.place(x=70,y=230)
var1=IntVar()
Checkbutton(ws,text="Male",variable=var1).place(x=235,y=230)
var2=IntVar()
Checkbutton(ws,text="Female",variable=var2).place(x=290,y=230)
defsubmit():
return Label(ws, text="Registration successfull").pack()
submitBtn=Button(ws,
text='Submit',width=20,bg='brown',fg='white',command=submit).place(x=180,y=
380)
ws.mainloop()
Output:
29 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
7. Demonstrate Exception in python:
try:
k = 5//0
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')
Output :
30 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
8. Drawing Line chart and Bar chat using Matplotlib.
Line Chart:
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
# This will plot a simple line chart
# with elements of x as x axis and y
# as y axis
plt.plot(x, y)
plt.title("Line Chart")
# Adding the legends
31 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
plt.legend(["Line"])
plt.show()
Output:
Bar Chart:
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
# This will plot a simple bar chart
plt.bar(x, y)
# Title to the plot
plt.title("Bar Chart")
# Adding the legends
plt.legend(["bar"])
plt.show()
Output :
32 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
9. Drawing Histogram and Pie chart using Matplotlib.
Histogram:
import matplotlib.pyplot as plt
import numpy as np
# Generate random data for the histogram
data = np.random.randn(1000)
# Plotting a basic histogram
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
# Adding labels and title
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Basic Histogram')
# Display the plot
plt.show()
Output:
33 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Pie Chart:
importmatplotlib.pyplotasplt
# data to display on plots
x=[1,2,3,4]
# this will explode the 1st wedge
# i.e. will separate the 1st wedge
# from the chart
e=(0.1,0,0,0)
# This will plot a simple pie chart
plt.pie(x,explode=e)
# Title to the plot
plt.title("Pie chart")
plt.show()
34 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Output:
10. Create Array using NumPy and Perform Operations on Array
import numpy as np
# Initializing the array
arr1 = np.arange(4, dtype = np.float64).reshape(2, 2)
print('First array:')
print(arr1)
print('\nSecond array:')
arr2 = np.array([12, 12])
print(arr2)
print('\nAdding the two arrays:')
print(np.add(arr1, arr2))
print('\nSubtracting the two arrays:')
print(np.subtract(arr1, arr2))
print('\nMultiplying the two arrays:')
print(np.multiply(arr1, arr2))
print('\nDividing the two arrays:')
print(np.divide(arr1, arr2))
Output:
35 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
11. Create Data Frame from Excel sheet using Pandas and Perform
Operations on Data Frames.
import pandas as pd
df = pd.read_excel('C:/Users/bella/OneDrive/Desktop/BATCH-4/BCA.xlsx')
print(df)
Output:
36 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
Head&tail
import pandas as pd
df = pd.read_excel('C:/Users/bella/OneDrive/Desktop/BATCH-4/BCA.xlsx')
print(df.head())
print(df.tail())
Output:
Sorting
import pandas as pd
df = pd.read_excel('C:/Users/bella/OneDrive/Desktop/BATCH-4/BCA.xlsx')
sorted_column = df.sort_values(['Campus ID'], ascending = True)
print(sorted_column.head(5))
Output:
37 Python Programming Lab(BCA302P) | BCA II Year/III Semester
The Yenepoya Institute of Arts, Science, Commerce and Management
A Constituent Unit of Yenepoya (Deemed to be University), Bangalore
38 Python Programming Lab(BCA302P) | BCA II Year/III Semester