Python Lab Manual 2024
Python Lab Manual 2024
Output Screen:
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:
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:
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.
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:
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: "))
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)
Output Screen:
Output Screen:
Q10. Write a program to demonstrate stack and queue operations using a list of numbers.
# Stack Implementation
stack = []
print("Stack Operations")
# Queue Implementation
queue = []
print("\nQueue Operations")
Output Screen:
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:
# 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)
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)]
Output Screen:
Output Screen:
print(key)
Output Screen:
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.
Output Screen:
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
Output Screen:
Output Screen:
Q20. Write a program to showcase use of Lambda functions, map, filter, reduce
function.
from functools import reduce
# 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)
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 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)
student1.add_grade(55)
student1.add_grade(69)
student1.add_grade(78)
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)
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__":
Output Screen:
# 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()
except FileNotFoundError:
print("Error: The source file was not found.")
except Exception as e:
print("An error occurred: ",e)
Output Screen: