1 Python Lab Manual
BCA 2.1 Lab: Manual of Python Programming
Q1. Write a program to demonstrate the usage of various arithmetic operators.
print("===========================")
x = int(input("Enter your first number: "))
y = int(input("Enter your second number: "))
sum = x + y
print("===========================")
print("RESULT SHOW")
print("Addition=",x+y)
print("Subtraction=",x-y)
print("Multiplication=",x*y)
print("Divistion=",x/y)
print("Modulus=",x%y)
print("Exponent=",x**y)
print("Floor Division=",x//y)
Output Screen:
Q2. Write a program that will convert various temperatures.
a) Fahrenheit to Centigrade
b) Centigrade to Fahrenheit
#a. Fahrenheit to Centigrade (Celsius)
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5 / 9
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
#b. Centigrade (Celsius) to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9 / 5) + 32
print(f"{celsius}°C is equal to {fahrenheit:.2f}°F")
September 30, 2024 1
BCA Department, Ravenshaw University, Cuttack-753014
2 Python Lab Manual
Output Screen
Q3. Write a program that will find the roots of a quadratic equation: ax² + bx + c = 0
import math
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
# Calculate the discriminant
discriminant = b**2 - 4*a*c
# Check if the discriminant is positive, zero, or negative
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print(f"The roots are real and different: {root1:.2f} and {root2:.2f}")
elif discriminant == 0:
root = -b / (2*a)
print(f"The roots are real and the same: {root:.2f}")
else:
real_part = -b / (2*a)
imaginary_part = math.sqrt(-discriminant) / (2*a)
print(f"The roots are complex: {real_part:.2f} ± {imaginary_part:.2f}i")
Output Screen:
For real and same roots:
For real and different roots:
For complex roots:
September 30, 2024 2
BCA Department, Ravenshaw University, Cuttack-753014
3 Python Lab Manual
Q4. Write a program that demonstrate the usage of various String functions.
str = "Welcome, Python Programming"
print("1. Length of the string:", len(str))
print("2. Lowercase:", str.lower())
print("3. Uppercase:", str.upper())
print("4. Capitalize:", str.capitalize())
print("5. Title Case:", str.title())
print("6. Occurrences of 'o':", str.count('o'))
print("7. Position of 'Python':", str.find('Python'))
print("8. Replace 'Python' with 'Java':", str.replace('Python', 'Java'))
str_with_spaces = " Hello, Python "
print("Original with spaces:", str_with_spaces)
print("9. After strip():", str_with_spaces.strip())
print("10. Split the string by spaces:", str.split())
words = ["Hello", "from", "Python"]
print("11. Join list into a string:", " ".join(words))
numeric_string = "12345"
print(f"12. Is '{numeric_string}' numeric?:", numeric_string.isdigit())
print("13. Does the string start with 'Hello'?:", str.startswith("Hello"))
print("14. Does the string end with 'Programming '?:", str.endswith("Programming"))
Output Screen:
September 30, 2024 3
BCA Department, Ravenshaw University, Cuttack-753014
4 Python Lab Manual
Q5. Write a program that will ask you to enter your name, through keyboard, and
perform following operations
a) Find the middle name
b) Find the last name (using string slicing)
c) Re-write the name with surname first.
full_name = input("Enter your full name: ")
# Split the name into parts (assuming the format is 'First Middle Last')
name_parts = full_name.split()
# a. Find the middle name
if len(name_parts) == 3:
middle_name = name_parts[1]
else:
middle_name = "No middle name"
print(f"Middle Name: {middle_name}")
# b. Find the last name using string slicing
last_name = name_parts[-1]
print(f"Last Name: {last_name}")
# c. Re-write the name with surname first
surname_first = f"{last_name}, {' '.join(name_parts[:-1])}"
print(f"Name with surname first: {surname_first}")
Output Screen:
Q6. Write a program to find out whether the integer entered by the user, through
the keyboard, is even or odd number.
x = int(input("Enter an integer number: "))
if (x % 2 == 0):
print(x ," is an even number.")
else:
print(x, "is an odd number.")
Output Screen:
September 30, 2024 4
BCA Department, Ravenshaw University, Cuttack-753014
5 Python Lab Manual
Q7. Find out the youngest among Shyam, Dugu and Ishan whose ages are entered
by the user through keyboard.
shyam_age = int(input("Enter Shyam's age: "))
dugu_age = int(input("Enter Dugu's age: "))
ishan_age = int(input("Enter Ishan's age: "))
# Find the youngest age
youngest_age = min(shyam_age, dugu_age, ishan_age)
# Determine who is the youngest
if youngest_age == shyam_age:
youngest_person = "Shyam"
elif youngest_age == dugu_age:
youngest_person = "Dugu"
else:
youngest_person = "Ishan"
print(f"The youngest is {youngest_person} with age {youngest_age} old.")
Output Screen:
Q8. Given three points (x1, y1), (x2, y2), (x3, y3), write a program to check all the
three points fall on one straight line.
# Function to check if three points are collinear
def are_points_collinear(x1, y1, x2, y2, x3, y3):
# Calculate the area using the determinant formula
return (y2 - y1) * (x3 - x2) == (y3 - y2) * (x2 - x1)
# Get the coordinates of the three points from the user
x1, y1 = map(float, input("Enter coordinates of point 1 (x1 y1): ").split())
x2, y2 = map(float, input("Enter coordinates of point 2 (x2 y2): ").split())
x3, y3 = map(float, input("Enter coordinates of point 3 (x3 y3): ").split())
# Check if the points are collinear
if are_points_collinear(x1, y1, x2, y2, x3, y3):
print("The points are collinear.")
else:
print("The points are not collinear.")
Output Screen:
September 30, 2024 5
BCA Department, Ravenshaw University, Cuttack-753014
6 Python Lab Manual
Q9. Write a program to demonstrate basic operations on the list.
my_list = [1, 7, 3, 6, 5, 9]
print("Display the Initial List:", my_list)
my_list.append(10) # Adding an element at the end
print("1. After appending 10:", my_list)
my_list.insert(0, 50) # Inserting an element at index 0
print("2. After inserting 50 at index 0:", my_list)
my_list.remove(3) # Removing the first occurrence of 30
print("3. After removing 3:", my_list)
popped_element = my_list.pop() # Popping the last element
print("4. Popped element:", popped_element)
print("5. After popping the last element:", my_list)
first_element = my_list[0] # Accessing the first element
print("6. First element:", first_element)
print("7. Iterating through the list:")
for item in my_list:
print(item)
print("8. Length of the list:", len(my_list))
my_list.sort() # Sorting the list in ascending order
print("9. Sorted List:", my_list)
my_list.reverse() # Reversing the list
print("10. Reversed List:", my_list)
Output Screen:
September 30, 2024 6
BCA Department, Ravenshaw University, Cuttack-753014
7 Python Lab Manual
Q10. Write a program to demonstrate stack and queue operations using a list of numbers.
# Stack Implementation
stack = []
print("Stack Operations")
# Push elements onto the stack
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack after push operations:", stack)
# Pop element from the stack
popped_element = stack.pop()
print("Popped element from stack:", popped_element)
print("Stack after pop operation:", stack)
# Peek at the top element of the stack
top_element = stack[-1] if stack else None
print("Top element of the stack:", top_element)
# Queue Implementation
queue = []
print("\nQueue Operations")
# Enqueue elements into the queue
queue.append(70)
queue.append(80)
queue.append(90)
print("Queue after enqueue operations:", queue)
# Dequeue element from the queue
dequeued_element = queue.pop(0) if queue else None
print("Dequeued element from queue:", dequeued_element)
print("Queue after dequeue operation:", queue)
# Peek at the front element of the queue
front_element = queue[0] if queue else None
print("Front element of the queue:", front_element)
Output Screen:
September 30, 2024 7
BCA Department, Ravenshaw University, Cuttack-753014
8 Python Lab Manual
Q11. Write a program to ask the data of five students that contain name, roll number,
age. Sort the list based on roll number of the student. [Note: Use list of lists].
students = []
for i in range(5):
name = input("Enter Name: ")
roll = int(input("Enter RollNo: "))
age = int(input("Enter Age: "))
students.append([name, roll, age])
# Sort the list by roll number (index 1)
students.sort(key=lambda x: x[1])
# Display the sorted list
print("\nStudents sorted by RollNo:")
for student in students:
print("Name: ", student[0], ": RollNo: " ,student[1], " : Age: ",student[2])
Output Screen:
Q12. Write a program to demonstrate basic operations on the tuple.
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)
# Accessing elements
print("Original Tuple:", my_tuple)
print("First Element:", my_tuple[0])
print("Last Element:", my_tuple[-1])
September 30, 2024 8
BCA Department, Ravenshaw University, Cuttack-753014
9 Python Lab Manual
# Slicing a tuple
print("Elements from index 1 to 3:", my_tuple[1:4])
print("All elements from index 2 onwards:", my_tuple[2:])
# Concatenating two tuples
tuple2 = (60, 70)
new_tuple = my_tuple + tuple2
print("Concatenated Tuple:", new_tuple)
# Finding the length of a tuple
print("Length of the tuple:", len(my_tuple))
# Checking membership
print("Is 20 in my_tuple?", 20 in my_tuple)
print("Is 100 in my_tuple?", 100 in my_tuple)
# Iterating through a tuple
print("Elements in the tuple:")
for element in my_tuple:
print(element)
# Tuple with mixed data types
mixed_tuple = ("Hello BCA ", 100, 3.14)
print("Mixed data type tuple:", mixed_tuple)
# Nested tuple
nested_tuple = (my_tuple, tuple2)
print("Nested tuple:", nested_tuple)
# Finding index of an element
index_of_30 = my_tuple.index(30)
print("Index of 30 in my_tuple:", index_of_30)
# Count occurrences of an element
count_of_20 = my_tuple.count(20)
print("Count of 20 in my_tuple:", count_of_20)
September 30, 2024 9
BCA Department, Ravenshaw University, Cuttack-753014
10 Python Lab Manual
Output Screen:
Q13. Store the data about the shares held by the user as tuples containing the
following information about shares: share name, cost price, number of shares,
selling price. Write a program to determine:
a) total cost of the portfolio
b) total amount gained or lost
# Sample data: (share name, cost price, number of shares, selling price)
shares = [("SBI ", 100, 50, 120), ("IDBI Ltd", 200, 30, 180), ("DEF ", 150, 40, 160)]
# a) Calculate the total cost of the portfolio
total_cost = sum(share[1] * share[2] for share in shares)
# b) Calculate the total amount gained or lost
total_gain_loss = sum((share[3] - share[1]) * share[2] for share in shares)
print("a. Total cost of the portfolio: ", total_cost)
print("b. Total amount gained or lost: ", total_gain_loss)
Output Screen:
September 30, 2024 10
BCA Department, Ravenshaw University, Cuttack-753014
11 Python Lab Manual
Q14 Write a program to demonstrate basic operations on the set.
# Creating a set
my_set = {10, 20, 30, 40, 50}
print("Original Set:", my_set)
# Adding elements to the set
my_set.add(60)
print("Set after adding 6:", my_set)
# Removing an element from the set
my_set.remove(30)
print("Set after removing 3:", my_set)
# Using discard (does not raise an error if element not found)
my_set.discard(10) # No error, even though 10 is not in the set
print("Set after discarding 10 (non-existent element):", my_set)
# Checking membership
print("Is 40 in the set?", 40 in my_set)
print("Is 10 in the set?", 10 in my_set)
# Union of two sets
set2 = {40, 50, 60, 70, 80}
union_set = my_set.union(set2)
print("Union of my_set and set2:", union_set)
# Intersection of two sets
intersection_set = my_set.intersection(set2)
print("Intersection of my_set and set2:", intersection_set)
# Difference of two sets
difference_set = my_set.difference(set2)
print("Difference of my_set and set2:", difference_set)
# Symmetric difference (elements in either set but not both)
symmetric_difference_set = my_set.symmetric_difference(set2)
print("Symmetric difference of my_set and set2:", symmetric_difference_set)
my_set.clear()
print("Set after clearing:", my_set)
September 30, 2024 11
BCA Department, Ravenshaw University, Cuttack-753014
12 Python Lab Manual
Output Screen:
Q15. Write a program to demonstrate basic operations on the dictionary.
# Creating a dictionary
student = { "name": "Anvi", "age": 23, "grade": "A++"}
print("Student Name:", student["name"])
print("Student Age:", student["age"])
# Adding a new key-value pair
student["subject"] = "BCA"
print("\nDictionary after adding subject:", student)
# Updating a value
student["grade"] = "O"
print("Dictionary after updating grade:", student)
# Removing a key-value pair
removed_subject = student.pop("subject")
print("\nRemoved subject:", removed_subject)
print("Dictionary after removing subject:", student)
# Checking if a key exists in the dictionary
print("\nIs 'age' key in the dictionary?", "age" in student)
print("Is 'subject' key in the dictionary?", "subject" in student)
# Iterating over keys and values
print("\nKeys in the dictionary:")
for key in student:
September 30, 2024 12
BCA Department, Ravenshaw University, Cuttack-753014
13 Python Lab Manual
print(key)
print("\nValues in the dictionary:")
for value in student.values():
print(value)
print("\nKey-Value pairs in the dictionary:")
for key, value in student.items():
print(f"{key}: {value}")
# Getting the value of a key using get() method (avoids KeyError)
print("\nUsing get() to access 'name':", student.get("name"))
print("Using get() to access non-existent 'subject':", student.get("subject", "Not
found"))
# Clearing the dictionary
student.clear()
print("\nDictionary after clearing:", student)
Output Screen:
September 30, 2024 13
BCA Department, Ravenshaw University, Cuttack-753014
14 Python Lab Manual
Q16. Create a dictionary to store data (name, roll number) of N students. The key
will be the roll number of the student and the value contains the data of the student
(in a list). Write a program that asks the user to enter a name of a Student, search
it in the dictionary and print the data of the Student if it is available otherwise
display an appropriate message.
# Create a dictionary to store student data
students = {}
n = int(input("Enter the number of students: "))
# Input student data
for _ in range(n):
name = input("Enter the name of the student: ")
roll_number = int(input("Enter the roll number of the student: "))
students[roll_number] = [name]
# Search for a student by name
search_name = input("\nEnter the name of the student to search: ")
# Search the dictionary
found = False
for roll_number, data in students.items():
if data[0].lower() == search_name.lower(): # Case insensitive search
print(f"Student found: Roll Number: {roll_number}, Name: {data[0]}")
found = True
break
# If student not found
if not found:
print("Student not found in the records.")
September 30, 2024 14
BCA Department, Ravenshaw University, Cuttack-753014
15 Python Lab Manual
Output Screen:
Q17. Write a program to demonstrate basic comprehensions on list, set and
dictionary.
# List
squares = [x**2 for x in range(1, 6)]
print("List - Squares:", squares)
# Set
square_set = {x**2 for x in range(1, 6)}
print("Set - Unique Squares:", square_set)
# Dictionary
square_dict = {x: x**2 for x in range(1, 6)}
print("Dictionary - Number:Square:", square_dict)
Output Screen:
Q18. Write a program to find the factorial value of a number entered by the user
using function.
# Function to calculate factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
num = int(input("Enter a number to find its factorial: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print("Factorial of ", num, " is: ",factorial(num))
September 30, 2024 15
BCA Department, Ravenshaw University, Cuttack-753014
16 Python Lab Manual
Output Screen:
Q19. Write a program to find the factorial of a number using recursion.
# Function to calculate factorial using recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number to find its factorial: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print("Factorial value : ", result)
Output Screen:
Q20. Write a program to showcase use of Lambda functions, map, filter, reduce
function.
from functools import reduce
# Sample list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 1. Using map() with a lambda function to square each number
squared = list(map(lambda x: x ** 2, numbers))
print("Squared Numbers:", squared)
# 2. Using filter() with a lambda function to get even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even_numbers)
# 3. Using reduce() with a lambda function to calculate the sum of the numbers
total_sum = reduce(lambda x, y: x + y, numbers)
print("Sum of Numbers:", total_sum)
# 4. Using reduce() to find the product of the numbers
product = reduce(lambda x, y: x * y, numbers)
print("Product of Numbers:", product)
September 30, 2024 16
BCA Department, Ravenshaw University, Cuttack-753014
17 Python Lab Manual
Output Screen:
Q21. Create a Python class called "Student" that encapsulates various attributes
of a student. Implement methods within the class to perform operations utilizing
these attributes.
class Student:
def __init__(self, name, roll, age):
self.name = name
self.roll = roll
self.age = age
self.grades = []
def add_grade(self, grade):
self.grades.append(grade)
def calculate_average(self):
if not self.grades:
return 0
return sum(self.grades) / len(self.grades)
def display_info(self):
average_grade = self.calculate_average()
print("Name: ", self.name)
print("Roll Number: ", self.roll)
print("Age: ", self.age)
print("Grades: " ,self.grades)
print("Average Grade: ", average_grade)
if __name__ == "__main__":
# Create a Student object
student1 = Student(name="Anvi Ray", roll=1001, age=20)
September 30, 2024 17
BCA Department, Ravenshaw University, Cuttack-753014
18 Python Lab Manual
student1.add_grade(55)
student1.add_grade(69)
student1.add_grade(78)
# Display student information
student1.display_info()
Output Screen:
Q22. Write a program to demonstrate both Static and Dynamic Polymorphism in
Python.
# Static Polymorphism: Method Overloading
class Rectangle:
def calculate(self, length, width=None):
if width is not None:
return 2 * (length + width) # Perimeter if both length and width are given
else:
return length * length # Area if only one argument is given (assuming it's a square)
# Dynamic Polymorphism: Method Overriding
class Shape:
def area(self):
pass
def perimeter(self):
pass
class RectangleShape(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
# Main Program
if __name__ == "__main__":
September 30, 2024 18
BCA Department, Ravenshaw University, Cuttack-753014
19 Python Lab Manual
print("# Demonstrate Static Polymorphism (Method Overloading)")
rect = Rectangle()
print("Area of square (side 5):", rect.calculate(5))
print("Perimeter of rectangle (length 5, width 3):", rect.calculate(5, 3))
print("# Demonstrate Dynamic Polymorphism (Method Overriding)")
rect_shape = RectangleShape(5, 3)
print("\nArea of rectangle (length 5, width 3):", rect_shape.area())
print("Perimeter of rectangle (length 5, width 3):", rect_shape.perimeter())
Output Screen:
Q23. Write a program to demonstrate exception handling mechanisms for various
types of exceptions.
def divide(a, b):
try:
# Attempt to divide two numbers
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except TypeError:
print("Error: Unsupported data type. Please enter numbers.")
else:
# If no exception occurs
print("Result: ", result)
finally:
# This block will always be executed
print("Execution of divide function complete.")
# Main Program
try:
# Input handling
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
divide(num1, num2)
September 30, 2024 19
BCA Department, Ravenshaw University, Cuttack-753014
20 Python Lab Manual
# Trigger a ValueError
number = int(input("Enter a valid integer: "))
except ValueError:
print("Error: Invalid input. Please enter a valid integer.")
except Exception as e:
# Catch any other unforeseen exceptions
print("An unexpected error occurred: ",e)
finally:
print("Program execution completed.")
Output Screen:
Q24. Write a program to read texts from a file and write them into another file.
try:
with open("demo.py", "r") as source_file:
content = source_file.read()
# Write to the destination file
with open("demo1.py", "w") as destination_file:
destination_file.write(content)
print("Content copied successfully.")
except FileNotFoundError:
print("Error: The source file was not found.")
except Exception as e:
print("An error occurred: ",e)
Output Screen:
September 30, 2024 20
BCA Department, Ravenshaw University, Cuttack-753014