Python Installation and Basic Programs
Python Installation and Basic Programs
PRACTICAL NO.1
Aim: How to install Python? Write the various steps.
Solution:
Step 1: Go to google, and search “Python idle download”. Click on the first result that appears, this is,
[Link].
Step 2: Select “Download” and click on the “Python 3.13.7”. The downloading will start.
Step 3: Go to download History and click on the python – 3.13.7. download for further installation of python
application on your system.
1
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
Step 4: The installation procedure will look like this.
Step 6: Open Python Idle on your system and print a simple program as an example.
2
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.2
Aim: Write a program to print “Hello World !” in Python.
Solution:
print("Hello , World !")
OUTPUT:
3
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.3
Aim: WAP to enter two integers, two floating numbers and then perform all arithmetic
operations on them.
Solution:
num1 = int(input("Enter the 1st integer number :"))
num2 = int(input("Enter the 2nd integer number :"))
4
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
OUTPUT:
5
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.4
Aim: Write a program to declare values to all datatypes and print their values with types.
Solution:
a = 107
b = 77.9
c = "Dishita"
d = True
e = None
print(f"Value : {a} Type :{type(a)}")
print(f"Value : {b} Type :{type(b)}")
print(f"Value : {c} Type :{type(c)}")
print(f"Value : {d} Type :{type(d)}")
print(f"Value : {e} Type :{type(e)}")
OUTPUT:
6
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.5
Aim: WAP to check whether a number is Armstrong or not.
Solution:
num = int(input("Enter a Number: "))
total = 0
temp = num
while temp > 0:
digit = temp % 10
total += digit ** 3
temp //= 10
if num == total:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
OUTPUT:
7
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.6
Aim: WAP to show the usage of break and continue.
Solution:
for num in range(1, 11):
if num % 2:
continue
if num > 7:
break
print(num)
OUTPUT:
8
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.7
Aim: WAP to show the usage of break and continue.
Solution:
num = int(input("Enter the number :"))
fact = 1
def recursion(num):
if num==1:
return num
else:
return num*recursion(num-1)
if num<0:
print("Factorial does not exist")
elif num==0:
print("Factorial of 0 is 1")
else:
print("Factorial is",recursion(num))
OUTPUT:
9
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.8
Aim: Print the elements of the following list using for loop.
Solution:
numbers = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print("Printing List:-")
for i in numbers:
print(i)
OUTPUT:
10
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.9
Aim: Search for a number x in a tuple using for loop.
Solution:
tup = (1,2,3,4,5,6,7,8,9,10)
x = int(input("Enter the item that you want to search:"))
count = 0
for i in tup:
if i == x:
count += 1
print(f"{x} is found in the tuple at the index {[Link](i)}")
if(count == 0):
print(f"{x} is not present in the tuple")
OUTPUT:
11
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.10
Aim: WAP to find the sum of numbers in the given range.
Solution:
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
total = 0
for i in range(start, end + 1):
total += i
print(f"The sum of numbers from {start} to {end} is: {total}")
OUTPUT:
12
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.11
Aim: WAP to Swap 2 Strings in python.
Solution:
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
print("After swapping:")
print("First string:", str1)
print("Second string:", str2)
OUTPUT:
13
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.12
Aim: WAP to demonstrate all the string functions.
Solution:
s = " Hello Python! I am Dishita Rawat. "
print("Original String:", s)
# Case functions
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Title case:", [Link]())
print("Capitalize:", [Link]())
print("Swapcase:", [Link]())
# Check functions
print("Is Alpha:", "Hello".isalpha())
print("Is Digit:", "12345".isdigit())
print("Is Alnum:", "Hello123".isalnum())
print("Is Lower:", "hello".islower())
print("Is Upper:", "HELLO".isupper())
print("Is Space:", " ".isspace())
# Justify / Alignment
print("Centered (width 30):", "Hello".center(30, "*"))
print("Left Justify (width 20):", "Hello".ljust(20, "-"))
print("Right Justify (width 20):", "Hello".rjust(20, "-"))
OUTPUT:
15
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.13
Aim: WAP to create and concatenate string and print a string and accessing sub string from
the given string.
Solution:
# Creating strings
str1 = "Ilay"
str2 = "Reigrow"
# Concatenation
result = str1 + " " + str2
# Printing
print("Concatenated String:", result)
OUTPUT:
16
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.14
Aim: WAP to print square of a positive number.
Solution:
num = int(input("Enter a positive number: "))
if num > 0:
print("Square of", num, "is:", num * num)
else:
print("Please enter a positive number.")
OUTPUT:
17
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.15
AIM: Write a program to print fibonacci series for first 15 number using recursion approach.
Solution:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
OUTPUT:
18
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.16
AIM: Write a program that creates a list from number 1-20 that is either divisible by 2 or 4.
Solution:
numbers = [x for x in range(1, 21) if x % 2 == 0 or x % 4 == 0]
print("Numbers divisible by 2 or 4 from 1-20:", numbers)
OUTPUT:
19
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.17
AIM: WAP that defines a list of countries that are members of BRICS. Check whether a
country is a member of BRICS or not. (BRICS: [Brazil, Russia, India, China, South Africa]).
Solution:
brics = ["Brazil", "Russia", "India", "China", "South Africa"]
if country in brics:
print(country, "is a member of BRICS.")
else:
print(country, "is NOT a member of BRICS.")
OUTPUT:
20
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.18
AIM: Write a program to print the index at which a particular value exists if the value exists
at multiple locations in the list, then print all the indices also count the number of times that
value is repeated in the list.
Solution:
values =[100,200,300,400,500,600,100,300]
search_value=int(input("Enter the value to search for:"))
indices=[]
count=0
for i in range(len(values)):
if values[i] == search_value:
[Link](i)
count+=1
if count > 0:
print("The value", search_value, "is found at indices.",indices)
print("The value",search_value,"is repeated",count,"times")
else:
print("The value",search_value,"is not found in the list.")
OUTPUT:
21
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.19
AIM: Write a program to print the following pattern:
*
**
***
****
*****
****
***
**
*
Solution:
n=5
for i in range(1,n+1):
print("*",i)
print("*",i)
OUTPUT:
22
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.20
AIM: Write a program to read 5 digit number and then display the number in the following
formats:
12345 1
2345 12
345 123
45 1234
5 12345
Solution:
number=input("Enter a 5-digit number:")
for i in range(5):
print(""*i+number[i:])
for i in range(5):
print(number[:i+1])
OUTPUT:
23
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.21
AIM: Write a program to check if the list contains a palindrome of elements, use copy method.
Solution:
list=list((1,2,3,1,2))
newlist=[Link]()
[Link]()
if newlist==list:
print(newlist,'is Palindrome')
else:
print(newlist,"is not palindrome")
OUTPUT:
24
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.22
AIM: Write a program to print the following pattern using nested loop:
*
**
***
****
*****
Solution:
for i in range(1,6):
for j in range(1,6):
if(j<=i):
print("*", end='')
else:
print(" ", end='')
print()
OUTPUT:
25
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.23
AIM: WAP that has nested list to store topper details. Edit the details and reprint the details.
Make it a menu driven program.
Solution:
toppers = [ ["Alice", 101, 95], ["Bob", 102, 92], ["Charlie", 103, 98] ]
def display_toppers():
print("-----------------------\n")
def edit_toppers():
display_toppers()
try:
return
except ValueError:
while True:
print("Menu:")
26
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
print("3. Exit")
if choice == '1':
display_toppers()
edit_toppers()
break
else:
OUTPUT:
27
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.24
AIM: Write a program to create tuples namely emp_name, designation and salary. Insert at
least 5 records and perform the following operations:
Solution:
print("Zipped Data:")
print(zipped_data)
print()
# Extract names of employees who are Designer and create a new tuple
print("Designers:")
print(designers)
print()
print("Sorted by Salary:")
print(sorted_by_salary)
print()
print(renamed_positions)
print()
print(updated_data)
OUTPUT
29
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.25
AIM: Create two lists, name and marks of 5 students and perform the following operations:
Solution:
# Step 2: Append marks list to names list (not recommended logically but following instructions)
combined_list = names + [str(mark) for mark in marks] # converting marks to string to append
[Link](["Fiona", "George"])
[Link]([95, 80])
[Link](3, "Hannah")
30
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
[Link](3, 87)
print("Names:", names)
print("Marks:", marks)
names_copy = [Link]()
marks_copy = [Link]()
names_slice = names[1:4]
if "Charlie" in names:
index = [Link]("Charlie")
[Link](index)
[Link](index)
print("Names:", names)
print("Marks:", marks)
if len(names) > 4:
[Link](4)
[Link](4)
print("Names:", names)
print("Marks:", marks)
if names:
[Link](0)
[Link](0)
print("Marks:", marks)
if marks:
[Link](0)
[Link]()
del names
OUTPUT:
32
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.26
AIM: Wap that creates a dictionary of radius of a circle and its circumference.
Solution:
import math
def calculate_circumference(radius):
circle_dict = {}
# Populate the dictionary with radius and circumference for a range of radius values
circle_dict[radius] = calculate_circumference(radius)
OUTPUT:
33
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.27
AIM: Write a program to store a sparse matrix as a dictionary.
Solution:
matrix = [
[0, 0, 3, 0],
[22, 0, 0, 0],
[0, 0, 0, 0],
[0, 17, 0, 0]
sparse_dict = {}
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
OUTPUT:
34
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.28
AIM: Write a program that has a dictionary of five states and their codes, for example: Delhi:
DL. Perform the following:
1. Add 5 more states to the previous dictionary.
2. Take input from the user to find a code for respective state.
3. If the state exists code is printed.
4. Set a default value “Sorry, No idea”.
Solution:
states = {
"Delhi": "DL", "Karnataka": "KA","Maharashtra": "MH",
"Tamil Nadu": "TN", "West Bengal": "WB"
}
[Link]({
"Punjab": "PB", "Gujarat": "GJ",
"Rajasthan": "RJ", "Kerala": "KL", "Bihar": "BR"
})
state_name = input("Enter the name of the state: ")
code = [Link](state_name, "Sorry, No idea")
print(f"Code for {state_name}: {code}")
OUTPUT:
35
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.29
AIM: Create a dictionary whose keys are month names and whose values are member of days
in the corresponding months, and perform the following tasks:
1. Ask the user to enter a month name and use a dictionary to tell them how many days are in
the month.
2. Print all the keys in the alphabetical order.
3. Print all the months with 31 days.
4. Print the keys value pairs sorted by number of days in each month.
Solution:
months = {
"January": 31, "February": 28, "March": 31,"April": 30,
"May": 31, "June": 30, "July": 31, "August": 31,
"September": 30, "October": 31, "November": 30, "December": 31
}
# 1. Ask user to enter a month and tell how many days it has
month_input = input("Enter the name of a month: ")
days = [Link](month_input, "Sorry, no data available for that month")
print(f"Number of days in {month_input}: {days}")
# 2. Print all keys (month names) in alphabetical order
print("\nMonths in alphabetical order:")
for month in sorted([Link]()):
print(month)
# 3. Print all the months with 31 days
print("\nMonths with 31 days:")
for month, day_count in [Link]():
if day_count == 31:
print(month)
# 4. Print the key-value pairs sorted by the number of days
print("\nMonths sorted by number of days:")
for month, day_count in sorted([Link](), key=lambda x: x[1]):
print(f"{month}: {day_count}")
OUTPUT:
36
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
37
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.30
AIM: Write a program to find intersection, union symmetric difference between two sets.
Solution:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Find intersection (elements common to both sets)
intersection = [Link](set2)
# Find union (all elements from both sets, no duplicates)
union = [Link](set2)
# Find symmetric difference (elements in either set, but not in both)
sym_diff = set1.symmetric_difference(set2)
# Print results
print(f"Set 1: {set1}")
print(f"Set 2: {set2}")
print(f"Intersection: {intersection}")
print(f"Union: {union}")
print(f"Symmetric Difference: {sym_diff}")
OUTPUT:
38
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.31
AIM- Write a program that creates two sets one of even number in range 1-10 and other has
all composite numbers in range 1-20. Demonstrate the use all() function, issuperset() function,
len() function and sum() function on the sets.
Solution:
set={2,4,6,8,10}
composite={4,6,8,10,12,14,16,18,20}
print("Even numbers (1-10):", set)
print("Composite numbers (1-20):", set)
# Demonstrate all() function: check if all even numbers are > 0
print("Are all even numbers > 0?", all(x > 0 for x in set))
# Demonstrate issuperset() function
print("Is composite_set a superset of even_set?", [Link](set))
# Demonstrate len() function
print("Number of even numbers:", len(set))
print("Number of composite numbers:", len(composite))
print("Sum of even numbers:", sum(set))
print("Sum of composite numbers:", sum(composite))
OUTPUT:
39
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.32
AIM: Write a program to add two integers using functions.
Solution:
# Function to add two integers
def add_numbers(a, b):
return a + b
# Input from user
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))
# Function call
result = add_numbers(num1, num2)
# Display the result
print("The sum of", num1, "and", num2, "is:", result)
OUTPUT:
40
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.33
AIM: Write a program to create local and global variables.
Solution:
# Global variable
x = 560
def my_function():
# Local variable
y=5
print("Inside function:")
print("Global variable x =", x) # Accessing global variable
print("Local variable y =", y)
# Call the function
my_function()
# Outside the function
print("\nOutside function:")
print("Global variable x =", x)
OUTPUT:
41
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.34
AIM: Write a program to demonstrate access of the variable in inner and outer function.
Solution:
def outer_function():
outer_var = "I am from the outer function"
def inner_function():
# Accessing the outer variable
print("Accessing from inner function:", outer_var)
42
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.35
AIM: Write a program to demonstrate the use of call by value and call by reference.
Solution:
def call_by_value(num):
num = 200
print("Inside call_by_value function, num:",num)
def call_by_reference(my_list):
my_list.append(100)
print("Inside call_by_reference, list:",my_list)
num=100
print("Before calling call_by_value,num:",num)
call_by_value(num)
print("After calling call_by_value,num:",num)
my_list=[1,2,3]
print("\nBefore call_by_reference,list:",my_list)
call_by_reference(my_list)
print("After calling call_by_reference,list:",my_list)
OUTPUT:
43
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.36
AIM: Write a program to add two variables using lambda function.
Solution:
x = lambda a , b : a+b
#this prints the result of calling the lambda function with arguments 5 and 142
print(x(5,142))
print(x(1000,123456))
OUTPUT:
44
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.37
AIM: Write a program that uses lambda function to find the sum of first 10 natural numbers.
Solution:
# Lambda function to find the sum of first 10 natural numbers
total = lambda n: sum(range(1, n + 1))
# Finding the sum of first 10 natural numbers
result = total(10)
# Printing the result
print("The sum of the first 10 natural numbers is:", result)
OUTPUT:
45
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.38
AIM: WAP to sum the series:-1/1!+4/2!+27/3!+...
Solution:
import math
def sum_series(n):
total_sum = 0
for i in range(1, n+1):
term = (i**i) / [Link](i)
total_sum += term
return total_sum
n = int(input("Enter the number of terms: "))
result = sum_series(n)
print(f"The sum of the series for {n} terms is: {result}")
OUTPUT:
46
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.39
AIM: Write a program to print at least 6 functions from math module.
Solution:
import math
print("The value of pi is: ",[Link])
print("The square root of 1000 is: ",[Link](1000))
print("1065.46546 when rounded to the nearest integer will be: ",[Link](1065.46546))
print("The factorial of 10 is: ",[Link](10))
print("The greatest common divisor for 20 and 100 is: ",[Link](20,100))
print("The truncated integer part of 1065.46546 will be: ",[Link](1065.46546))
print("The result of x to the power y will be: ",[Link](3,4))
OUTPUT:
47
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.40
AIM: Write a program to display the functionality of random function using random module.
Solution:
import random
# Generating a random integer between 1 and 10
random_number = [Link](1, 10)
print("Random number between 1 and 10:", random_number)
# Generating a random floating-point number between 0 and 1
random_float = [Link]()
print("Random float between 0 and 1:", random_float)
fruits = ['apple', 'banana', 'cherry', 'mango', 'orange']
# Picking a random fruit from the list
random_fruit = [Link](fruits)
print("Randomly selected fruit:", random_fruit)
[Link](fruits)
print("Shuffled list of fruits:", fruits)
OUTPUT:
48
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.41
AIM: Write a program to create a NumPy 1D array.
Solution:
import numpy as np
numbers = [Link]([1, 2, 3, 4, 5])
print("1D NumPy array:", numbers)
OUTPUT:
49
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.42
AIM: Write a program to sum all elements in an array using NumPy.
Solution:
import numpy as np
values = [Link]([10, 20, 30, 40])
total_sum = [Link](values)
print("Sum of all elements:", total_sum)
OUTPUT:
50
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.43
AIM: Write a program for NumPy to convert a 1D array of 8 elements in a 2D array.
Solution:
import numpy as np
original_array = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
# Converting the 1D array into a 2D array (with 2 rows and 4 columns)
array_2d = original_array.reshape(2, 4)
print("2D NumPy array:\n", array_2d)
OUTPUT:
51
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.44
AIM: You are given two NumPy arrays, array1 and array2 representing the heights (in cm)
and weights (in kg) of a group of individuals, respectively. Write a Python function that takes
these two arrays as input and returns a new NumPy array containing the Body Mass Index
(BMI) for each individual. The formula for BMI is:
BMI = Weight (kg) / (Height (m)) 2
Solution:
import numpy as np
def calculate_bmi(heights, weights):
# Convert heights from cm to meters
heights_in_meters = heights / 100
# Calculate BMI using the formula
bmi = weights / (heights_in_meters ** 2)
return bmi
array1 = [Link]([170, 160, 180]) # Heights in cm
array2 = [Link]([70, 60, 75]) # Weights in kg
# Calculating BMI
bmi_result = calculate_bmi(array1, array2)
print("BMI for each individual:", bmi_result)
OUTPUT:
52
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.45
AIM: Write a program to add a list to a NumPy array.
Solution:
import numpy as np
num_array = [Link]([1, 2, 3])
# Creating a list to add
new_list = [4, 5, 6]
# Adding the list to the NumPy array using [Link]
combined_array = [Link](num_array, new_list)
print("Combined NumPy array:", combined_array)
OUTPUT:
53
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.46
AIM: Write a program to extract first n columns of a NumPy matrix.
Solution:
import numpy as np
matrix = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Function to extract first n columns
def extract_columns(matrix, n):
return matrix[:, :n]
result = extract_columns(matrix, 2)
print("First 2 columns of the matrix:\n", result)
OUTPUT:
54
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.47
AIM: Write a program to implement various operations on NumPy array.
Solution:
import numpy as np
numbers = [Link]([10, 20, 30, 40, 50])
sum_elements = [Link](numbers)
print("Sum of all elements:", sum_elements)
mean_value = [Link](numbers)
print("Mean value:", mean_value)
max_value = [Link](numbers)
print("Maximum value:", max_value)
min_value = [Link](numbers)
print("Minimum value:", min_value)
std_deviation = [Link](numbers)
print("Standard Deviation:", std_deviation)
OUTPUT:
55
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.48
AIM: Write a program to implement aggregation function in NumPy array.
Solution:
import numpy as np
data = [Link]([5, 15, 25, 35, 45])
total_sum = [Link](data)
print("Sum of all elements:", total_sum)
average = [Link](data)
print("Mean of all elements:", average)
max_value = [Link](data)
print("Maximum value:", max_value)
min_value = [Link](data)
print("Minimum value:", min_value)
product = [Link](data)
print("Product of all elements:",product)
OUTPUT:
56
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.49
AIM: You are given a 2D NumPy Array that represents a grayscale image, where each element
corresponds to the intensity of a pixel. The array is structures as follows:
image=[Link]([[10,20,30,40],
[50, 60, 70, 80],
[90, 100, 110, 120],
[130, 140, 150, 160]])
i. Using array slicing, extract the central 2X2 section of the image.
ii. Calculate the average pixel intensity of the extracted section.
Solution:
import numpy as np
image = [Link]([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120],
[130, 140, 150, 160]])
# i. Using array slicing to extract the central 2x2 section
central_section = image[1:3, 1:3]
print("Central 2x2 section:\n", central_section)
# ii. Calculating the average pixel intensity of the extracted section
average_intensity = [Link](central_section)
print("Average pixel intensity of central section:", average_intensity)
OUTPUT:
57
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.50
AIM: Create a text file and perform the following the operations:
1. Open the file and read the contents from the file.
2. Check if the file exists or not
3. Write the content and display
4. Append the content to the existing file and display it
5. Remove the file
Solution:
import os
# 1. Creating and Writing to a text file
file_name = "[Link]"
# Opening the file in write mode and writing content
with open(file_name, 'w') as file:
[Link]("Hello, this is a test file.\n")
[Link]("We are learning file handling in Python.\n")
print("File created and content written.")
# 2. Checking if the file exists
if [Link](file_name):
print(f"'{file_name}' exists.")
else:
print(f"'{file_name}' does not exist.")
# 3. Reading the content from the file
with open(file_name, 'r') as file:
content = [Link]()
print("\nContents of the file:\n", content)
# 4. Appending content to the existing file
with open(file_name, 'a') as file:
[Link]("This line is appended to the file.\n")
# Reading the content again to verify append
with open(file_name, 'r') as file:
58
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
updated_content = [Link]()
print("\nUpdated content after appending:\n", updated_content)
# 5. Removing the file
[Link](file_name)
print(f"'{file_name}' has been deleted.")
OUTPUT:
59
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.51
AIM: Write a Python script using Matplotlib to create a pie chart that displays the distribution
of fruits in a basket: 30 apples, 20 bananas, 25 oranges, and 15 grapes. Include a legend and
assign custom colors to each slice with the fruits names and their corresponding percentages.
Solution:
import [Link] as plt
fruits = ['Apples', 'Bananas', 'Oranges', 'Grapes']
quantities = [33, 15, 30, 25]
colors = ['red', 'yellow', 'orange', 'purple']
[Link](figsize=(6, 6))
[Link](quantities, labels=fruits, colors=colors, autopct='%1.1f%%', startangle=90)
[Link](fruits, title='Fruits', loc='best')
[Link]('Distribution of Fruits in a Basket')
[Link]()
OUTPUT:
60
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.52
AIM: Create a bar chart using Matplotlib to display the number of students enrolled in
different courses:
Math (50), Science (40), History (30), and Art (20).
Solution:
import [Link] as plt
courses = ['PYTHON', 'JAVA', 'C++', 'PHP']
enrollment = [60, 55, 78, 14]
colors = ['#ff6347', '#1e90ff', '#32cd32', '#ff8c00'] # Custom colors
[Link](figsize=(8, 5))
[Link](courses, enrollment, color=colors)
# Adding title and labels
[Link]('Number of Students Enrolled in Different Courses')
[Link]('Courses')
[Link]('Number of Students')
[Link]()
OUTPUT:
61
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
PRACTICAL NO.53
AIM: Create a bar chart that includes different colours for each bar, custom tick labels, and a
grid.
Solution:
import [Link] as plt
categories = ['PYTHON', 'JAVA', 'C++', 'PHP']
values = [60, 55, 78, 14]
colors = ['#C797F0', '#8867A8', '#8438C2', '#DDC7F0']
tick_labels = ['PYTHON', 'JAVA', 'C++', 'PHP']
[Link](figsize=(8, 5))
bars = [Link](categories, values, color=colors)
[Link]('Number of Students Enrolled in Different Courses')
[Link]('Courses')
[Link]('Number of Students')
[Link](ticks=range(len(categories)), labels=tick_labels)
[Link](True, axis='y', linestyle='--', alpha=0.7) # Grid on y-axis with dashed lines
[Link]()
OUTPUT:
62
DISHITA RAWAT ENROLL NO-01521102024 PP FILE (BCA-III-E1)
63