Python Lab (4)
Python Lab (4)
Algorithm
1. Start the program.
2. Input two numbers from the user.
3. Perform addition of the two numbers.
4. Perform subtraction of the two numbers.
5. Perform multiplication of the two numbers.
6. Perform division of the two numbers.
7. Display the results of the operations.
8. End the program.
Source code
# Step 1: Start the program
# Step 2: Input two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Step 3: Perform addition
addition = num1 + num2
# Step 4: Perform subtraction
subtraction = num1 - num2
# Step 5: Perform multiplication
multiplication = num1 * num2
# Step 6: Perform division
# Ensure the second number is not zero to avoid division by zero error
if num2 != 0:
division = num1 / num2
else:
division = "undefined (division by zero)"
# Step 7: Display the results of the operations
print(f"The addition of {num1} and {num2} is: {addition}")
print(f"The subtraction of {num1} and {num2} is: {subtraction}")
print(f"The multiplication of {num1} and {num2} is: {multiplication}")
print(f"The division of {num1} and {num2} is: {division}")
# Step 8: End the program
Output
Enter the first number: 10
Enter the second number: 5
The addition of 10.0 and 5.0 is: 15.0
The subtraction of 10.0 and 5.0 is: 5.0
The multiplication of 10.0 and 5.0 is: 50.0
The division of 10.0 and 5.0 is: 2.0
Result
Algorithm
Source code
# Step 1: Start the program
average = sum_numbers / 3
0utput
Enter the first number: 12
Result
The python program for finding the sum and average of three numbers is compiled
and executed successfully.
Exp No:3 Date:
Write python program to display last digit of a
number
Aim
Algorithm
Source code
# Step 1: Start the program
# Step 2: Input a number from the user
number = int(input("Enter a number: "))
# Step 3: Find the last digit of the number using the modulus operator
last_digit = number % 10
# Step 4: Display the last digit
print(f"The last digit of {number} is: {last_digit}")
# Step 5: End the program
Output
Enter a number: 12345
The last digit of 12345 is: 5
Result
The python program for finding the last digit of numbers is compiled and
executed successfully.
Exp No:4 Date:
String Operations in Python
Aim
Algorithm
uppercase_string = original_string.upper()
lowercase_string = original_string.lower()
if substring in original_string:
substring_position = original_string.find(substring)
else:
substring_position = -1
reversed_string = original_string[::-1]
if substring_position != -1:
else:
Output
Enter a string: Hello
Enter another string to concatenate: world
Enter a substring to find: ello
Original String: Hello
Concatenated String: Helloworld
Uppercase String: HELLO
Lowercase String: hello
Substring 'ello' found at position: 1
Reversed String: olleH
Result
Source code
str1=input("enter string")
lower=upper=""
for char in str1:
if char.islower():
lower+=char
else:
upper+=char
result =lower + upper
print(result)
Output
enter stringhappyNewYEAR
happyewNYEAR
Result:
The python program for arranging the characters of a string so that all
lowercase letters come first is compiled & executed successfully.
Exp No:6 Date:
Count all letters, digits and special characters
from a given string
Aim
Write a python program to count all letters,digits and special characters from
a given string
Algorithm:
● Start a program
● Get string from User
● Count numbers of letters,digits and special characters
● Print each count
● Stop program
Source code
# Input the string
str1 = input("Enter a string: ")
# Initialize counters
letter_count = 0
digit_count = 0
special_count = 0
Result
The python program for counting all letters,digits and special characters from a
given string is compiled & executed successfully.
Exp No:7 Date:
Python program to interchange first and last
elements in a list
Aim
To write a python program to interchange first and last element in a list
Algorithm
1. Create a list with some elements.
2. Calculate the size of the list.
3. If the list is empty or contains only one element, do nothing as no
interchange is needed.
4. Use a temporary variable to swap the first element (newList[0]) with the last
element (newList[size - 1]).
5. Print the list with the first and last elements interchanged.
Source code
Output
Aim
To write a python program to combining list of strings
Algorithm:
Source code
l1=["Th","i","python "]
l2=["is","s","programming"]
l3=[]
for i in range(len(l1)):
l3.append(l1[i]+l2[i])
print(l3)
Output
['This', 'is', 'python programming']
Result
The python program for combining lists of strings is compiled & executed
successfully
Exp No:9 Date:
Sum of number digits in List
Aim
The aim of this program is to calculate the sum of the digits of each number in a
list and print the results.
Algorithm
Source code
# Step 1: Initialize the list
res = []
sum_digits = 0
sum_digits += int(digit)
res.append(sum_digits)
# Step 4: Print the result
Algorithm
Source code
# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the last element
print("Largest element is:", list1[-1])
Output
Largest element is: 99
Result
Exp No:11 Date:
Python Tuple Operations
Aim
Write a python program to do python tuple operations
Algorithm
Here, below are the Python tuple operations.
● Accessing of Python Tuples
● Concatenation of Tuples
● Slicing of Tuple
● Deleting a Tuple
Source code
# Accessing Tuple
# with Indexing
Tuple1 = tuple("Geeks")
print("\nFirst element of Tuple: ")
print(Tuple1[0])
# Tuple unpacking
Tuple1 = ("Geeks", "For", "Geeks")
# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')
Tuple3 = Tuple1 + Tuple2
# Printing first Tuple
print("Tuple 1: ")
print(Tuple1)
# Printing Second Tuple
print("\nTuple2: ")
print(Tuple2)
# Printing Final Tuple
print("\nTuples after Concatenation: ")
print(Tuple3)
# Slicing of a Tuple
# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('GEEKSFORGEEKS')
# Removing First element
print("Removal of First Element: ")
print(Tuple1[1:])
# Reversing the Tuple
print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])
# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9])
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
Output
Tuple 1:
(0, 1, 2, 3)
Tuple2:
('Geeks', 'For', 'Geeks')
Result
Exp No:12 Date:
Extracting Specific Keys from a Dictionary
Aim
To Write a Python Program for Extracting Specific Keys from a Dictionary
Algorithm
Input:
Initialize:
Output:
Source Code
# Original dictionary
original_dict = {
'name': 'John',
'age': 30,
'city': 'New York',
'job': 'Engineer'}
# Keys to extract
keys_to_extract = ['name', 'city']
# Extracting specific keys
extracted_dict = {key: original_dict[key] for key in keys_to_extract}
print(extracted_dict)
Output:
Result :
The python program for extracting specific keys from a Dictionary is compiled &
executed successfully
Exp No:13 Date:
Set Operations
Aim:
To write a program to perform the following operations in: Sample_Set ={“Yellow
“,”Orange”,”Black”},
Sample_list =[“Blue”,”Green”,”Red”]
Algorithm:
Add an element to the set.
Remove an element from the set.
Add an element to the list.
Remove an element from the list.
Convert the list to a set.
Convert the set to a list.
Find the union of the set and the list (after converting the list to a set).
Find the intersection of the set and the list (after converting the list to a set).
Source Code
# 7. Find the union of the set and the list (after converting the list to a set)
union_set = Sample_Set.union(Sample_Set_from_list)
print("Union of set and list:", union_set)
# 8. Find the intersection of the set and the list (after converting the list to a set)
intersection_set = Sample_Set.intersection(Sample_Set_from_list)
print("Intersection of set and list:", intersection_set)
Output
Algorithm
1. Initialize an empty list `divisible_by_5`.
2. Iterate through numbers from 100 to 999.
a. If a number is divisible by 5, add it to `divisible_by_5`.
3. Randomly select 3 numbers from `divisible_by_5`.
4. Print the 3 randomly selected numbers.
Source code
import random
# Step 1: Initialize the range and the list to store numbers divisible by 5
start = 100
end = 999
divisible_by_5 = []
Output
Three random integers between 100 and 999 that are divisible by 5: [905, 490, 240]
Result
The python program to generate 3 random integer between 100 and 999 which is
divisible by 5 is compiled & executed successfully
Exp 15
Exception Handling Using try...except
Aim:
Algorithm
Initialize Variables:
Try Block:
Exception Handling:
● If an exception occurs (e.g., division by zero), control moves to the except block.
● Inside the except block, print the message: "Error: Denominator cannot be 0."
End Program:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
Try Block:
Exception Handling:
End Program:
● The program terminates after printing the error message for the
IndexError.
Source code
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
Algorithm
1. Initialize Variables:
1. Set file_name to "example.txt".
2. Set new_file_name to "renamed_example.txt".
2. Create and Write to a File:
1. Open file_name in write mode.
2. Write the following lines to the file:
■ "This is a new file."
■ "File manipulation in Python is straightforward."
3. Close the file.
3. Read the Content of the File:
1. Open file_name in read mode.
2. Read the content of the file.
3. Print the content to the console.
4. Close the file.
4. Append to the File:
1. Open file_name in append mode.
2. Write the following line to the file:
■ "Let's append some more text to the file."
3. Close the file.
5. Read the Content of the File Again:
1. Open file_name in read mode.
2. Read the updated content of the file.
3. Print the updated content to the console.
4. Close the file.
6. Rename the File:
1. Rename file_name to new_file_name using the os.rename() function.
2. Print a message indicating the file has been renamed.
7. Delete the File:
1. Delete new_file_name using the os.remove() function.
2. Print a message indicating the file has been deleted.
import os
To write a python program to create create multiple object of class and methods of class
Algorithm
# define a class
class Employee:
# define a property
employee_id = 0
Python Methods
Algorithm
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)
# create object of Room class
study_room = Room()
# assign values to all the properties
study_room.length = 42.5
study_room.breadth = 30.8
Aim
Algorithm:
Source code
my_account.deposit(500)
my_account.display_balance()
my_account.withdraw(300)
my_account.display_balance()
Output
Private Attribute:
Public Methods:
Access Control:
Object Creation:
def display_balance(self):
print(f"Account Holder: {self.account_holder}")
print(f"Current Balance: ${self.__balance:.2f}")
@abstractmethod
def display_info(self):
pass
def area(self):
return self.__width * self.__height
def display_info(self):
print(f"Rectangle: Width = {self.__width}, Height =
{self.__height}, Area = {self.area()}")
def area(self):
import math
return math.pi * (self.__radius ** 2)
def display_info(self):
print(f"Circle: Radius = {self.__radius}, Area = {self.area()}")
Algorithm
Define Base Class:
Create Objects:
Call Methods:
End:
● The program completes after printing the details of the Car and
Motorcycle objects.
Source code
# Base class
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Vehicle Brand: {self.brand}")
print(f"Vehicle Model: {self.model}")
# Derived class
class Car(Vehicle):
def __init__(self, brand, model, num_doors):
# Call the constructor of the base class
super().__init__(brand, model)
self.num_doors = num_doors
def display_info(self):
# Call the display_info method of the base class
super().display_info()
print(f"Number of Doors: {self.num_doors}")
# Derived class
class Motorcycle(Vehicle):
def __init__(self, brand, model, has_sidecar):
# Call the constructor of the base class
super().__init__(brand, model)
self.has_sidecar = has_sidecar
def display_info(self):
# Call the display_info method of the base class
super().display_info()
print(f"Has Sidecar: {self.has_sidecar}")
print("\nMotorcycle Information:")
my_motorcycle.display_info()
Output
Car Information:
Vehicle Brand: Toyota
Vehicle Model: Camry
Number of Doors: 4
Motorcycle Information:
Vehicle Brand: Harley-Davidson
Vehicle Model: Sportster
Has Sidecar: True
Polymorphism in Class Methods
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years
old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years
old.")
def make_sound(self):
print("Bark")
Method Overriding
from math import pi
class Shape:
def __init__(self, name):
self.name = name
def area(self):
pass
def fact(self):
return "I am a two-dimensional shape."
def __str__(self):
return self.name
class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length
def area(self):
return self.length**2
def fact(self):
return "Squares have each angle equal to 90 degrees."
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return pi*self.radius**2
a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
EXP 22 DATE
DATA VISUALIZATION
AIM
DEFINITION
PROGRAM
PROGRAM
3.BAR CHARTS: A Bar chart or bar graph is a chart or graph that presents
categorical data with rectangular bars with heights or lengths proportional to the
values that they represent. A bar plot is a way of representing data where the length
of the bars represents the magnitude/size of the feature/variable.
Example:
PROGRAM
4.BOX PLOTS: A Box plot (or box-and-whisker plot) shows the distribution of
quantitative data in a way that facilitates comparisons between variables or across
levels of a categorical variable. Box plot shows the quartiles of the dataset while
the whiskers extend encompass the rest of the distribution but leave out the points
that are the outliers.
Example:
PROGRAM
5.SCATTER PLOTS: A Scatter chart, also called a scatter plot, is a chart that
shows the relationship between two variables.
Example:
PROGRAM