Assi. Prof.
MANESH PATEL
PRESIDENT INSTITUTE OF COMPUTER APPLICAION COLLEGE, SHAYONA CAMPUS, A’BAD.
B C A SEM: 5 Practical Python– Unit 2 Python
1 Create a program to retrieve, display and update only a
range of elements from an array using indexing and
slicing in arrays
import array
# Create an integer array
arr = [Link]('i', [10, 20, 30, 40, 50, 60, 70, 80])
print("Original Array:")
print(arr)
# using slicing
start = int(input("Enter start index of the range: "))
end = int(input("Enter end index of the range: "))
print("Elements in the selected range:")
print(arr[start:end]) # slicing
# Update elements
for i in range(start, end):
new_value = int(input(f"Enter new value for element at index {i}
(current value: {arr[i]}): "))
arr[i] = new_value Original Array:
array('i', [10, 20, 30, 40, 50, 60, 70, 80])
print("Updated Array:") Enter start index of the range: 2
print(arr) Enter end index of the range: 5
Elements in the selected range:
array('i', [30, 40, 50])
Enter new value for element at index 2 (current value: 30): 300
Enter new value for element at index 3 (current value: 40): 400
Enter new value for element at index 4 (current value: 50): 500
Updated Array:
array('i', [10, 20, 300, 400, 500, 60, 70, 80])
PREPARED BY: PATEL MANESH - [Link](CA & IT) Contact: 90165 17796 1
PATEL MANESH
2 Write a program to understand various methods of array
class mentioned: append, insert, remove, pop, index,
,tolist and count.
import array
# Create an integer array
arr = [Link]('i', [10, 20, 30, 40, 50])
print("Original Array:", arr)
# 1. append() - Add an element at the end
[Link](60)
print("After append(60):", arr)
# 2. insert() - Insert element at specific index
[Link](2, 25) # Insert 25 at index 2
print("After insert(2, 25):", arr)
# 3. remove() - Remove first occurrence of value
[Link](40)
print("After remove(40):", arr)
# 4. pop() - Remove and return element at index (default last)
popped_element = [Link]()
print("After pop():", arr)
print("Popped element:", popped_element)
# 5. index() - Get index of first occurrence of value
index_of_25 = [Link](25)
print("Index of 25:", index_of_25)
# 6. tolist() - Convert array to list
list_version = [Link]()
print("Array as list:", list_version)
# 7. count() - Count occurrences of a value
count_20 = [Link](20)
print("Count of 20 in array:", count_20)
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 2
PATEL MANESH
Original Array: array('i', [10, 20, 30, 40, 50])
After append(60): array('i', [10, 20, 30, 40, 50, 60])
After insert(2, 25): array('i', [10, 20, 25, 30, 40, 50, 60])
After remove(40): array('i', [10, 20, 25, 30, 50, 60])
After pop(): array('i', [10, 20, 25, 30, 50])
Popped element: 60
Index of 25: 2
Array as list: [10, 20, 25, 30, 50]
Count of 20 in array: 1
3 Write a program to sort the array elements using bubble
sort technique.
import array
# Create an array
arr = [Link]('i', [20, 40, 10, 30])
print("Original Array:")
print(arr)
# Bubble Sort Algorithm
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
# Swap elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print("Sorted Array:")
print(arr) Original Array:
array('i', [20, 40, 10, 30])
Sorted Array:
array('i', [10, 20, 30, 40])
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 3
PATEL MANESH
4 Create a program to search the position of an element
in an array using index() method of array class.
import array
# Create an array
arr = [Link]('i', [10, 20, 30, 40, 50, 60])
print("Array Elements:", arr)
# Input element to search
element = int(input("Enter the element to search: "))
try:
# Find index (position) of the element
position = [Link](element)
print(f"Element {element} found at index {position}")
except ValueError:
print(f"Element {element} not found in the array.")
Array Elements: array('i', [10, 20, 30, 40, 50, 60])
Enter the element to search: 30
Element 30 found at index 2
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 4
PATEL MANESH
5 Write a program to generate prime numbers with the
help of a function to test prime or not.
import math
def is_prime(num):
if num <= 1:
return False
for i in range(2, int([Link](num)) + 1):
if num % i == 0:
return False
return True
def generate_primes(limit):
primes = []
for number in range(2, limit + 1):
if is_prime(number):
[Link](number)
return primes
# Example usage:
upper_limit = 10
prime_numbers = generate_primes(upper_limit)
print(f"Prime numbers up to {upper_limit}: {prime_numbers}")
Prime numbers up to 10: [2, 3, 5, 7]
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 5
PATEL MANESH
6 Write a python program that removes any repeated
items from a list so that each item appears at most
once. For instance, the list [1,1,2,3,4,3,0,0] would
become [1,2,3,4,0].
def duplicate(original):
unique_list = []
for item in original:
if item not in unique_list: [10, 20, 30, 40, 70]
unique_list.append(item)
return unique_list
no = [10, 10, 20, 30, 40, 30, 70, 70]
result = duplicate(no)
print(result)
7 Write a program to pass a list to a function and display
it.
def Manish(abc):
print("My values are==== ")
for item in abc:
print(item) [10, 20, 30, 40, 50]
No = [10, 20, 30, 40, 50]
Manish(No)
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 6
PATEL MANESH
8 Write programs to demonstrate the use of Positional
Argument, keyword argument , default arguments ,
variable length arguments
def position(name, age):
print(f"Hello {name}, you are {age} years old.")
# Calling the function using positional arguments
position("Manoj",50)
def key(name, age):
print(f"Hello {name}, you are {age} years old.")
# Using keyword arguments
key(age=35, name="Jay")
def default(name, age=20):
print(f"Hello {name}, you are {age} years old.")
# with one argument uses the default value for age
default("Khushi")
# Calling with both arguments overrides the default
default("Ashvin", 22)
def count(*numbers):
for i in numbers:
print(i)
# Calling the function with different number of arguments
count(1, 2, 3)
count(10, 20)
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 7
PATEL MANESH
Hello Manoj, you are 50 years old.
Hello Jay, you are 35 years old.
Hello Khushi, you are 20 years old.
Hello Ashvin, you are 22 years old.
1
2
3
10
20
9 Write a lambda/Anonymous function to find bigger
number in two given numbers
Max = lambda a, b : a if a > b else b
print(Max(50, 200)) 200
300
print(Max(300, 20))
10 Create a program name “[Link]” and implement
the functions DA, HRA, PF, and ITAX. Create another
program that uses the function of employee module and
calculates gross and net salaries of an employee
Save File 1 - [Link]
def da(basic_salary):
return 0.10 * basic_salary
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 8
PATEL MANESH
def hra(basic_salary):
return 0.15 * basic_salary
def pf(basic_salary):
return 0.08 * basic_salary
def itax(basic_salary):
return 0.05 * basic_salary
Save File 2 - [Link]
import employee
def calculate_salaries(basic_salary):
da_amount = [Link](basic_salary)
hra_amount = [Link](basic_salary)
pf_amount = [Link](basic_salary)
itax_amount = [Link](basic_salary)
gross_salary = basic_salary + da_amount + hra_amount
net_salary = gross_salary - pf_amount - itax_amount
return gross_salary, net_salary
# Main program
if __name__ == "__main__":
basic = float(input("Enter basic salary: "))
gross, net = calculate_salaries(basic)
print(f"\nGross Salary: {gross:.2f}")
print(f"Net Salary: {net:.2f}")
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 9
PATEL MANESH
Enter basic salary: 50000
Gross Salary: 62500.00
Net Salary: 56000.00
11 Write a program to create a list using range functions
and perform append, update and delete elements
operations in it.
No = list(range(1, 7))
print("Original List:", No)
# Append an element to the list
[Link](500)
print("After Append 500:", No)
# Update the 5th element (index 2)
No[2] = 50
print("After Updating 3th Element to 50:", No)
# Delete the 3rd element (index 3)
del No[3]
print("After Deleting 4rd Element:", No)
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 10
PATEL MANESH
Original List: [1, 2, 3, 4, 5, 6]
After Append 500: [1, 2, 3, 4, 5, 6, 500]
After Updating 3th Element to 50: [1, 2, 50, 4, 5, 6, 500]
After Deleting 4rd Element: [1, 2, 50, 5, 6, 500]
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 11
PATEL MANESH
12 Create a sample list of 7 elements and implement the
List methods mentioned: append, insert, copy, extend,
count, remove, pop, sort, reverse and clear.
sample_list = [5, 2, 9, 1, 5, 6, 3]
print("Original List:", sample_list)
# 1. append() - Add element to the end of the list
sample_list.append(7)
print("After append(7):", sample_list)
# 2. insert() - Insert element at a specific position
sample_list.insert(2, 10)
print("After insert(2, 10):", sample_list)
# 3. copy() - Create a shallow copy of the list
copied_list = sample_list.copy()
print("Copied List:", copied_list)
# 4. extend() - Extend list by appending elements from
another list
sample_list.extend([8, 4])
print("After extend([8, 4]):", sample_list)
# 5. count()
count_of_5 = sample_list.count(5)
print("Count of 5:", count_of_5)
# 6. remove() - Remove first occurrence of a value
sample_list.remove(5)
print("After remove(5):", sample_list)
sample_list.pop()
print("After pop:", sample_list)
sample_list.sort()
print("After sort:", sample_list)
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 12
PATEL MANESH
sample_list.reverse()
print("After reverse:", sample_list)
sample_list.clear()
print("After clear:", sample_list)
Original List: [5, 20, 90, 10, 5, 60, 30]
After append(7): [5, 20, 90, 10, 5, 60, 30, 7]
After insert(2, 10): [5, 20, 10, 90, 10, 5, 60, 30, 7]
Copied List: [5, 20, 10, 90, 10, 5, 60, 30, 7]
After extend([8, 4]): [5, 20, 10, 90, 10, 5, 60, 30, 7, 8, 4]
Count of 5: 2
After remove(5): [20, 10, 90, 10, 5, 60, 30, 7, 8, 4]
After pop: [20, 10, 90, 10, 5, 60, 30, 7, 8]
After sort: [5, 7, 8, 10, 10, 20, 30, 60, 90]
After reverse: [90, 60, 30, 20, 10, 10, 8, 7, 5]
After clear: []
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 13
PATEL MANESH
13 Write a program to create nested list and display its
elements.
nested_list = [
[10, 20, 30],
[40, 50],
[60, 70, 80, 90]
]
print("Nested List Elements:")
for i, sublist in enumerate(nested_list):
print(f"Sublist {i + 1}: ", end='')
for item in sublist:
print(item, end=' ')
print()
Nested List Elements:
Sublist 1: 10 20 30
Sublist 2: 40 50
Sublist 3: 60 70 80 90
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 14
PATEL MANESH
14 Write a program to accept elements in the form of a
tuple and display its minimum, maximum, sum and
average.
elements = tuple(map(int, input("Enter elements separated
by commas: ").split(',')))
# Calculate minimum, maximum, sum and average
minimum = min(elements)
maximum = max(elements)
total = sum(elements)
average = total / len(elements)
# Display results
print(f"Elements= {elements}")
print(f"Minimum= {minimum}")
print(f"Maximum= {maximum}")
print(f"Sum= {total}")
print(f"Average= {average}")
Enter elements separated by commas: 10,30,38,52,14,6
Elements= (10, 30, 38, 52, 14, 6)
Minimum= 6
Maximum= 52
Sum= 150
Average= 25.0
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 15
PATEL MANESH
15 Create a program to sort tuple with nested tuples
nested_tuple = ((3, 'Manish'), (1, 'Ashvin'), (2, 'Nivanshi'), (5, 'Bina'))
print("Original tuple=", nested_tuple)
# Sort the tuple by the first element of each nested tuple
sort = tuple(sorted(nested_tuple, key=lambda x: x[0]))
print("Sorted tuple=", sort)
Original tuple= ((3, 'Manish'), (1, 'Ashvin'), (2, 'Nivanshi'), (5, 'Bina'))
Sorted tuple= ((1, 'Ashvin'), (2, 'Nivanshi'), (3, 'Manish'), (5, 'Bina'))
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 16
PATEL MANESH
16 Create a dictionary that will accept cricket players
name and scores in a match. Also we are retrieving runs
by entering the player’s name.
player_scores = {}
# Accept number of players
no = int(input("Enter the number of players: "))
# Get player names and scores
for i in range(no):
name = input("Enter player name: ")
score = int(input(f"Enter score for {name}: "))
player_scores[name] = score
# Retrieve score by player name
search_name = input("\nEnter player name to get their score: ")
if search_name in player_scores:
print(f"{search_name} scored {player_scores[search_name]} runs.")
else:
print(f"No score found for player: {search_name}")
Enter the number of players: 2
Enter player name: Manish
Enter score for Manish: 80
Enter player name: Ashvin
Enter score for Ashvin: 60
Enter player name to get their score: Ashvin
Ashvin scored 60 runs.
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 17
PATEL MANESH
17 Write a program to convert the elements of two lists into
keyvalue pairs of a dictionary
head = ['name', 'salary', 'city']
data = ['Manish', 2000, 'baroda']
# Convert lists into a dictionary
combine = dict(zip(head, data))
print("Combine Datas== ")
print(combine)
Combine Datas==
{'name': 'Manish', 'salary': 2000, 'city': 'baroda'}
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 18
PATEL MANESH
18 Create a python function to accept python function as a
dictionary and display its elements
def name():
return "I am Manish!"
def city():
return "Baroda"
def salary():
return 15000
data = {
"Name Function": name,
"City Function": city,
"salary Function": salary
}
def display(data):
print("Displaying function dictionary elements:\n")
for key, func in [Link]():
print("Key=", key)
print("Function Name=", func.__name__)
print("Function Output=", func())
print("*" * 25)
# Call the function
display(data)
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 19
PATEL MANESH
Displaying function dictionary elements:
Key= Name Function
Function Name= name
Function Output= I am Manish!
*************************
Key= City Function
Function Name= city
Function Output= Baroda
*************************
Key= salary Function
Function Name= salary
Function Output= 15000
*************************
s
PREPARED BY: PATEL MANESH - [Link](CA & IT), [Link] Contact: 90165 17796 20