Exp No:1 Date:
Addition, subtraction, multiplication, and
division of two numbers using Python.
Aim
To perform the addition, subtraction, multiplication, and division of two numbers
using Python.
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
The python program for addition , subtraction ,multiplication and division is
compiled and executed successfully.
Exp No:2 Date:
Sum and average of three numbers using
Python
Aim
To find the sum and average of three numbers using Python.
Algorithm
1. Start the program.
2. Input three numbers from the user.
3. Calculate the sum of the three numbers.
4. Calculate the average of the three numbers.
5. Display the sum and the average.
6. End the program.
Source code
# Step 1: Start the program
# Step 2: Input three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Step 3: Calculate the sum of the three numbers
sum_numbers = num1 + num2 + num3
# Step 4: Calculate the average of the three numbers
average = sum_numbers / 3
# Step 5: Display the sum and the average
print(f"The sum of {num1}, {num2}, and {num3} is: {sum_numbers}")
print(f"The average of {num1}, {num2}, and {num3} is: {average}")
# Step 6: End the program
0utput
Enter the first number: 12
Enter the second number: 13
Enter the third number: 14
The sum of 12.0, 13.0, and 14.0 is: 39.0
The average of 12.0, 13.0, and 14.0 is: 13.0
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
To display the last digit of a given number using Python.
Algorithm
1. Start the program.
2. Input a number from the user.
3. Find the last digit of the number using the modulus operator.
4. Display the last digit.
5. End the program.
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
To perform various string operations such as concatenation, conversion to
uppercase, conversion to lowercase, finding a substring, and reversing the string
using Python.
Algorithm
1. Start the program.
2. Input a string from the user.
3. Perform the following string operations:
○ Concatenation with another string.
○ Convert the string to uppercase.
○ Convert the string to lowercase.
○ Find a substring within the string.
○ Reverse the string.
4. Display the results of the operations.
5. End the program.
# Step 1: Start the program
# Step 2: Input a string from the user
original_string = input("Enter a string: ")
# Step 3: Perform string operations
# 3.1: Concatenate with another string
additional_string = input("Enter another string to concatenate: ")
concatenated_string = original_string + additional_string
# 3.2: Convert the string to uppercase
uppercase_string = original_string.upper()
# 3.3: Convert the string to lowercase
lowercase_string = original_string.lower()
# 3.4: Find a substring within the string
substring = input("Enter a substring to find: ")
if substring in original_string:
substring_position = original_string.find(substring)
else:
substring_position = -1
# 3.5: Reverse the string
reversed_string = original_string[::-1]
# Step 4: Display the results of the operations
print(f"\nOriginal String: {original_string}")
print(f"Concatenated String: {concatenated_string}")
print(f"Uppercase String: {uppercase_string}")
print(f"Lowercase String: {lowercase_string}")
if substring_position != -1:
print(f"Substring '{substring}' found at position: {substring_position}")
else:
print(f"Substring '{substring}' not found in the original string.")
print(f"Reversed String: {reversed_string}")
# Step 5: End the program
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
The string operations in python are compiled and executed successfully.
Exp No:5 Date:
Reorder the characters in the string to
prioritize lowercase letters first.
Aim
To write a python program to reorder the characters in the string to prioritize
lowercase letters first.
Algorithm
● Start the program
● Get string from the user
● Search for the lowercase letters and append to list ’lower’
● Search for the uppercase letters and append to list ’upper’
● Combine list lower and list upper as result
● Print result
● Stop the program
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
# Iterate through each character in the string
for char in str1:
if char.isalpha():
letter_count += 1
elif char.isdigit():
digit_count += 1
else:
special_count += 1
# Output the counts
print("Letters:", letter_count)
print("Digits:", digit_count)
print("Special characters:", special_count)
Output
Enter a string: AbcdSE123@#
Letters: 6
Digits: 3
Special characters: 2
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
# Python3 program to swap first
newList = [12, 35, 9, 56, 24]
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
print(newList)
Output
[24, 35, 9, 56, 12]
Result
Exp 8 Date
Combining Lists of Strings
Aim
To write a python program to combine list of string
Aim
To write a python program to combining list of strings
Algorithm:
1. Create two lists, l1 and l2, with elements to be concatenated.
2. Create an empty list l3 to store the concatenated results.
3. Use a loop to iterate through the indices of the lists.
4. For each index, concatenate the elements from l1 and l2 and append the
result to l3.
5. Print the list l3 containing the concatenated elements.
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
1. Initialize the List:Create a list with some integer elements.
2. Print the Original List:Print the original list.
3. Calculate the Sum of Digits:
● Iterate through each element in the list.
● Convert each element to a string and iterate through its digits.
● Convert each digit back to an integer and sum them up.
● Append the result to a new list.
Source code
# Step 1: Initialize the list
test_list = [12, 67, 98, 34]
# Step 2: Print the original list
print("The original list is : " + str(test_list))
# Step 3: Calculate the sum of digits
res = []
for ele in test_list:
sum_digits = 0
for digit in str(ele):
sum_digits += int(digit)
res.append(sum_digits)
# Step 4: Print the result
print("List Integer Summation : " + str(res))
Exp No:10 Date:
Find Largest Number in a List
Aim
Write a python program to find largest number in a list
Algorithm
● Create a list with some integer elements.
● Use the sort method to sort the list in ascending order.
● Access the last element of the sorted list, which will be the
largest element.
● Print the largest element.
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
First element of Tuple:
G
Values after unpacking:
Geeks
For
Geeks
Tuple 1:
(0, 1, 2, 3)
Tuple2:
('Geeks', 'For', 'Geeks')
Tuples after Concatenation:
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
Tuple after sequence of Element is reversed:
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
Printing elements between Range 4-9:
('S', 'F', 'O', 'R', 'G')
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:
● A dictionary original_dict with key-value pairs.
● A list keys_to_extract containing the keys that need to be extracted.
Initialize:
● An empty dictionary extracted_dict.
Iterate through keys_to_extract:
● For each key in keys_to_extract:
○ Check if the key exists in original_dict.
○ If key exists, add key and its corresponding value from original_dict
to extracted_dict.
Output:
● The dictionary extracted_dict contains the extracted key-value pairs.
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:
{'name': 'John', 'city': 'New York'}
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
# Initialize the set and the list
Sample_Set = {"Yellow", "Orange", "Black"}
Sample_list = ["Blue", "Green", "Red"]
# 1. Add an element to the set
Sample_Set.add("Purple")
print("Set after adding 'Purple':", Sample_Set)
# 2. Remove an element from the set
Sample_Set.discard("Orange") # Using discard to avoid KeyError if the element is not present
print("Set after removing 'Orange':", Sample_Set)
# 3. Add an element to the list
Sample_list.append("Yellow")
print("List after adding 'Yellow':", Sample_list)
# 4. Remove an element from the list
Sample_list.remove("Green")
print("List after removing 'Green':", Sample_list)
# 5. Convert the list to a set
Sample_Set_from_list = set(Sample_list)
print("Set converted from list:", Sample_Set_from_list)
# 6. Convert the set to a list
Sample_list_from_set = list(Sample_Set)
print("List converted from set:", Sample_list_from_set)
# 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
Set after adding 'Purple': {'Purple', 'Orange', 'Black', 'Yellow'}
Set after removing 'Orange': {'Purple', 'Black', 'Yellow'}
List after adding 'Yellow': ['Blue', 'Green', 'Red', 'Yellow']
List after removing 'Green': ['Blue', 'Red', 'Yellow']
Set converted from list: {'Blue', 'Red', 'Yellow'}
List converted from set: ['Purple', 'Black', 'Yellow']
Union of set and list: {'Purple', 'Red', 'Black', 'Blue', 'Yellow'}
Intersection of set and list: {'Yellow'}
Result
The Python program to perform the following operation in :Sample_Set ={“Yellow
“,”Orange”,”Black”}, Sample_list =[“Blue”,”Green”,”Red”] is compiled &
executed successfully
Exp No:14 Date:
Printing 3 random integers between 100 and 999
divisible by 5
Aim
To write a python program to generate 3 random integers between 100 and 999
divisible by 5.
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 = []
# Step 2: Filter numbers that are divisible by 5
for num in range(start, end + 1):
if num % 5 == 0:
divisible_by_5.append(num)
# Step 3: Randomly select 3 numbers from the filtered list
random_selection = random.sample(divisible_by_5, 3)
# Step 4: Print the selected numbers
print("Three random integers between 100 and 999 that are divisible by 5:", random_selection)
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:
To write a python program to exception handling using try…except
Algorithm
Initialize Variables:
● Set the numerator to 10.
● Set the denominator to 0.
Try Block:
● Enter the try block to attempt to perform a division operation.
● Calculate the result by dividing the numerator by the denominator.
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:
● The program terminates after printing the error message.
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
Catching Specific Exceptions in Python
Algorithm
Initialize List:
● Create a list called even_numbers with the elements [2, 4, 6, 8].
Try Block:
● Enter the try block to attempt accessing the element at index 5 of
the even_numbers list.
● Since the list only contains elements at indices 0 to 3, this will
raise an IndexError.
Exception Handling:
● ZeroDivisionError Check: The program checks if a
ZeroDivisionError has occurred. If so, it would print:
"Denominator cannot be 0." However, this does not happen here.
● IndexError Check: The program then checks if an IndexError has
occurred. Since accessing index 5 is out of bounds, control
moves to this block.
● Inside the IndexError block, print the message: "Index Out of
Bound."
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.")
# Output: Index Out of Bound
Exp No:16 Date:
File Handling in Python
Aim
To Write a Python Program for file handling
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
# Step 1: Create and Write to a File
file_name = 'example.txt'
with open(file_name, 'w') as file:
file.write("This is a new file.\n")
file.write("File manipulation in Python is straightforward.\n")
# Step 2: Read the Content of the File
with open(file_name, 'r') as file:
content = file.read()
print("Content of the file after creation and writing:")
print(content)
# Step 3: Append to the File
with open(file_name, 'a') as file:
file.write("Let's append some more text to the file.\n")
# Step 4: Read the Content of the File Again After Appending
with open(file_name, 'r') as file:
content = file.read()
print("\nContent of the file after appending:")
print(content)
# Step 5: Rename the File
new_file_name = 'renamed_example.txt'
os.rename(file_name, new_file_name)
print(f"\nFile renamed from {file_name} to {new_file_name}")
# Step 6: Delete the File
os.remove(new_file_name)
print(f"\nFile {new_file_name} has been deleted.")
Exp 17
Python Program Demonstrating Class and Object
Usage
Create Multiple Objects of Python Class
Aim
To write a python program to create create multiple object of class and methods of class
Algorithm
● Create a class named Employee with a property called employee_id.
● Create two objects: employee1 and employee2 of the Employee class.
● Assign 1001 to employee1.employee_id.
● Assign 1002 to employee2.employee_id.
● Print employee1.employee_id.
● Print employee2.employee_id.
● The program finishes after printing the employee IDs.
# define a class
class Employee:
# define a property
employee_id = 0
# create two objects of the Employee class
employee1 = Employee()
employee2 = Employee()
# access property using employee1
employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")
# access properties using employee2
employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")
Python Methods
Algorithm
● Create a class named Room.
● Inside the class, define properties length and breadth with initial values of 0.0.
● Define a method calculate_area that computes and prints the area of the room using the formula:
length * breadth.
● Create an object named study_room of the Room class.
● Assign the value 42.5 to study_room.length.
● Assign the value 30.8 to study_room.breadth.
● Call the calculate_area method on the study_room object, which computes and prints the area.
● The program ends after calculating and printing the area of the room.
# 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
# access method inside class
study_room.calculate_area()
Exp 18
Python Program for Managing a Bank Account
Aim
Algorithm:
○ Create a class named BankAccount.
○ Define properties account_holder and balance with an initial
value for balance set to 0.
○ Initialize account_holder and balance with values provided
when creating an object.
○ Define a method deposit to add a specified amount to the
balance.
○ Check if the deposit amount is positive.
○ Update the balance and print the deposit amount.
○ Define a method withdraw to subtract a specified amount from the
balance.
○ Check if the amount is positive and does not exceed the current
balance.
○ Update the balance and print the withdrawal amount or show an
error message if the conditions are not met.
○ Define a method display_balance to print the
account_holder name and the current balance.
○ Create an instance of BankAccount with an account holder's name
and an initial balance.
○ Call display_balance to show the initial balance.
○ Use the deposit method to add funds to the account and update the
balance.
○ Call display_balance again to show the updated balance.
○ Use the withdraw method to withdraw funds and update the
balance.
○ Call display_balance to show the updated balance after
withdrawal.
○ Attempt a withdrawal that exceeds the balance and handle the error
appropriately.
○ The program completes after performing and displaying the results of
the deposit and withdrawal operations.
Source code
# Create a class for a BankAccount
class BankAccount:
# Constructor method to initialize account details
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance
# Method to deposit money into the account
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited: ${amount:.2f}")
else:
print("Deposit amount must be positive.")
# Method to withdraw money from the account
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew: ${amount:.2f}")
else:
print("*Insufficient balance or invalid amount.")
# Method to display the current balance
def display_balance(self):
print(f"Account Holder: {self.account_holder}")
print(f"Current Balance: ${self.balance:.2f}")
# Create an object of BankAccount class
my_account = BankAccount("John Doe", 1000)
# Call methods on the BankAccount object
my_account.display_balance()
my_account.deposit(500)
my_account.display_balance()
my_account.withdraw(300)
my_account.display_balance()
my_account.withdraw(1500) # Invalid withdraw (insufficient balance)
Output
Account Holder: John Doe
Current Balance: $1000.00
Deposited: $500.00
Account Holder: John Doe
Current Balance: $1500.00
Withdrew: $300.00
Account Holder: John Doe
Current Balance: $1200.00
Insufficient balance or invalid amount.
Exp 19
Python Program Demonstrating Data Hiding
Private Attribute:
● __balance is a private attribute. It is intended to be accessed only
within the BankAccount class.
Public Methods:
● deposit: Adds money to the balance.
● withdraw: Subtracts money from the balance if there are sufficient
funds.
● display_balance: Displays the account holder's name and balance.
Access Control:
● The __balance attribute is not directly accessible from outside the
class. Attempts to access it directly will result in an AttributeError.
Object Creation:
● An instance my_account is created, and methods are called to modify
and display the balance.
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: ${amount:.2f}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew: ${amount:.2f}")
else:
print("Insufficient balance or invalid amount.")
def display_balance(self):
print(f"Account Holder: {self.account_holder}")
print(f"Current Balance: ${self.__balance:.2f}")
# Create an object of BankAccount class
my_account = BankAccount("Alice Smith", 1000)
# Access methods that interact with private attributes
my_account.display_balance()
my_account.deposit(500)
my_account.withdraw(300)
my_account.display_balance()
# Attempt to access private attribute directly (will raise an
AttributeError)
try:
print(my_account.__balance)
except AttributeError:
print("Cannot access private attribute directly.")
Exp 20
Python Program Demonstrating Data
Abstraction
Algorithm
Abstract Base Class (Shape):
● Defined using the ABC (Abstract Base Class) module.
● Contains abstract methods area and display_info that must be implemented
by any subclass.
Concrete Class (Rectangle):
● Inherits from Shape.
● Implements the area method to calculate the area of the rectangle.
● Implements the display_info method to print the rectangle’s dimensions and
area.
● Uses private attributes __width and __height to hide internal details.
Concrete Class (Circle):
● Inherits from Shape.
● Implements the area method to calculate the area of the circle.
● Implements the display_info method to print the circle’s radius and area.
● Uses a private attribute __radius to hide internal details.
Object Creation and Usage:
● Instances of Rectangle and Circle are created.
● The display_info method is called on each object to show their respective
details.
from abc import ABC, abstractmethod
# Abstract base class
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def display_info(self):
pass
# Concrete class for Rectangle
class Rectangle(Shape):
def __init__(self, width, height):
self.__width = width
self.__height = height
def area(self):
return self.__width * self.__height
def display_info(self):
print(f"Rectangle: Width = {self.__width}, Height =
{self.__height}, Area = {self.area()}")
# Concrete class for Circle
class Circle(Shape):
def __init__(self, radius):
self.__radius = radius
def area(self):
import math
return math.pi * (self.__radius ** 2)
def display_info(self):
print(f"Circle: Radius = {self.__radius}, Area = {self.area()}")
# Create objects of the concrete classes
rectangle = Rectangle(5, 3)
circle = Circle(4)
# Use the objects
rectangle.display_info()
circle.display_info()
Output
Rectangle: Width = 5, Height = 3, Area = 15
Circle: Radius = 4, Area = 50.26548245743669
Exp 21 DATE
Python Program Demonstrating Inheritance
Algorithm
Define Base Class:
● Class Name: Vehicle
● Properties: brand, model
● Method: display_info
○ Print the brand and model of the vehicle.
Define Derived Class (Car):
● Inherit from: Vehicle
● Additional Properties: num_doors
● Constructor:
○ Initialize brand and model using the base class constructor.
○ Initialize num_doors.
● Method: display_info
○ Call the display_info method of the base class.
○ Print the num_doors.
Define Derived Class (Motorcycle):
● Inherit from: Vehicle
● Additional Properties: has_sidecar
● Constructor:
○ Initialize brand and model using the base class constructor.
○ Initialize has_sidecar.
● Method: display_info
○ Call the display_info method of the base class.
○ Print the has_sidecar.
Create Objects:
● Object 1: my_car (instance of Car)
○ Initialize with brand, model, and num_doors.
● Object 2: my_motorcycle (instance of Motorcycle)
○ Initialize with brand, model, and has_sidecar.
Call Methods:
● Call display_info on my_car to print its details.
● Call display_info on my_motorcycle to print its details.
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}")
# Create objects of the derived classes
my_car = Car("Toyota", "Camry", 4)
my_motorcycle = Motorcycle("Harley-Davidson", "Sportster", True)
# Call the methods on the objects
print("Car Information:")
my_car.display_info()
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")
cat1 = Cat("Kitty", 2.5)
dog1 = Dog("Fluffy", 4)
for animal in (cat1, dog1):
animal.make_sound()
animal.info()
animal.make_sound()
Polymorphism and Inheritance
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
To Implement data visualization using python
DEFINITION
1.LINE PLOTS: A line plot is used to represent quantitative values over a
continuous interval or time period. It is generally used to depict trends on how the
data has changed over time.
Example:
PROGRAM
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [1, 5, 3, 5, 7, 8]
plt.plot(x, y)
plt.show()
2.HISTOGRAMS: Histograms represent the frequency distribution of a dataset. It
is a graph showing the number of observations within each given interval.
PROGRAM
import matplotlib.pyplot as plt
population_age=[22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,1
11,115,80]
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age, bins, histtype='bar', rwidth=0.8)
plt.xlabel('age groups')
plt.ylabel('Number of people')
plt.title('Histogram')
plt.show()
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
from matplotlib import pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],label="BMW",width=.5)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],label="Audi", color='r',width=.5)
plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance (kms)')
plt.title('Information')
plt.show()
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
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7]
y=[1,2,4,5,3,6,9]
z=[x,y]
plt.boxplot(z,labels=["A","B"],showmeans=True)
plt.show()
5.SCATTER PLOTS: A Scatter chart, also called a scatter plot, is a chart that
shows the relationship between two variables.
Example:
PROGRAM
import matplotlib.pyplot as plt
x=[1,1.5,2,2.5,3,3.5,3.6]
y=[7.5,8,8.5,9,9.5,10,10.5]
x1=[8,8.5,9,9.5,10,10.5,11]
y1=[3,3.5,3.7,4,4.5,5,5.2]
plt.scatter(x,y, label='high income low saving',color='r')
plt.scatter(x1,y1,label='low income high savings',color='b')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()