244MCC112L-MCA Python Lab Manual (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

MASTER OF COMPUTER APPLICATIONS

244MCC112L - PYTHON PROGRAMMING LABORATORY RECORD

S.NO Name of the Exercise Date Sign


Python programming using simple statements and expressions
1.
(exchange the values of two variables, circulate the values of n 19.09.24
variables, distance between two points).

2. Scientific problems using Conditionals and Iterative loops. 24.09.24

3. Linear search and Binary search 24.09.24

4. Selection sort, Insertion sort 01.10.24

5. Merge sort, Quick Sort 08.10.24

6. Implementing applications using Lists, Tuples. 22.10.24

7. Implementing applications using Sets, Dictionaries. 19.11.24

8. Implementing programs using Functions. 21.11.24

9. Implementing programs using Strings. 21.11.24

Implementing programs using written modules and Python Standard


10. 26.11.24
Libraries (pandas, numpy, Matplotlib, scipy)

11. Implementing real-time/technical applications using File handling. 28.11.24

Implementing real-time/technical applications using Exception


12. 03.12.24
handling.

13. Creating and Instantiating classes 03.12.24


1. Python programming using simple statements and expressions (exchange the values of
two variables, circulate the values of n variables, distance between two points).

Ex. No: 1(a) Date: 19.09.24

Exchange the Values of Two Variables (Simple Statements and Expressions)

Aim:
To understand and implement a basic concept of swapping two values without using a temporary
variable, and to demonstrate simple variable manipulation techniques in Python.

Algorithm:

• Initialize two variables, a and b, with values.


• Print the original values of a and b.
• Assign the value of a to a temporary variable temp.
• Assign the value of b to a.
• Assign the value of temp to b.
• Print the swapped values of a and b.

Program:

def swap_values(a, b):


# Swap using tuple unpacking
a, b = b, a
return a, b

# Example
a=5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a, b = swap_values(a, b)
print(f"After swap: a = {a}, b = {b}")

Output:

Before swap: a = 5, b = 10
After swap: a = 10, b = 5

Result:

Thus the above program was executed successfully.


Ex. No: 1(b) Date: 19.09.24

Circulate the Values of n Variables

Aim:
To practice manipulating collections of variables (lists) by shifting or rotating elements, which helps
in understanding indexing and list operations in Python.

Algorithm:

• Input the list of n variables into a list arr.


• Store the last element of the list in a temporary variable temp.
• Shift all elements in the list to the right by one position.
• Place the value of temp (the last element) in the first position.
• Output the updated list arr after the circulation.
• End the algorithm.

Program:

def circulate_values(arr):

# Rotate left by 1
return arr[1:] + [arr[0]]

# Example
arr = [1, 2, 3, 4, 5]
print(f"Before circulation: {arr}")
arr = circulate_values(arr)
print(f"After circulation: {arr}")

Output:

Before circulation: [1, 2, 3, 4, 5]


After circulation: [2, 3, 4, 5, 1]

Result:

Thus the above program was executed successfully.


Ex. No: 1(c) Date: 19.09.24

Distance Between Two Points

Aim:
To apply basic geometry using the distance formula and demonstrate how to use mathematical
functions in Python, such as square root and exponentiation.

Algorithm:

• Open a python file


• Take the coordinates of two points (x1, y1) and (x2, y2).
• Use the distance formula:
d=(x2−x1)2+(y2−y1)2d = \sqrt{(x2 - x1)^2 + (y2 - y1)^2}d=(x2−x1)2+(y2−y1)2
• Create a function and apply the formula for two points.
• Return the distance.

Program:

import math

def distance_between_points(x1, y1, x2, y2):


return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

# Example
x1, y1 = 1, 2
x2, y2 = 4, 6
print(f"Distance: {distance_between_points(x1, y1, x2, y2)}")

Output:

Distance: 5.0

Result:

Thus the above program was executed successfully.


Ex. No: 2 Date: 24.09.24

2. Scientific problems using Conditionals and Iterative loops.

Aim:

To do a Python program for implementing scientific problems using Conditionals and Iterative loops.

Algorithm:

• Define the conditions or parameters (e.g., checking for prime numbers or calculating
factorial).
• Set up the loop structure (for/while loop) for iteration.
• Within the loop, use conditionals (if/else) to check and handle specific conditions.
• For example, if checking for a prime, check if the number has any divisors other than 1 and
itself.
• Perform required operations (e.g., add to a sum or accumulate results) within the loop.
• Exit the loop and display results after completion.

Program:

# Function to check if a number is prime


def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# Function to calculate factorial of a number


def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact

# Input numbers
num = int(input("Enter a number to check if it is prime: "))
fact_num = int(input("Enter a number to calculate its factorial: "))

# Check if the number is prime


if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

# Calculate the factorial of the number


print(f"The factorial of {fact_num} is {factorial(fact_num)}.")
Output:

Enter a number to check if it is prime: 7


Enter a number to calculate its factorial: 5
7 is a prime number.
The factorial of 5 is 120.

Result:

Thus the above program was executed successfully


3. Linear Search and Binary Search

Ex. No: 3(a) Date: 24.09.24

Linear Search

Aim:

To understand the concept of sequential searching and how to efficiently find an element in an
unsorted list by checking each item one by one.

Algorithm:

• Define a list arr and an element target.


• Loop through each element of the list.
• Compare the current element with the target.
• If a match is found, return the index of the element.
• If the loop completes and no match is found, return -1 (element not found).
• Display the result (index or -1).

Program:

def linear_search(arr, target):

for i in range(len(arr)):
if arr[i] == target:
return i
return -1

# Example
arr = [1, 4, 6, 7, 8]
target = 6
print(f"Index of {target}: {linear_search(arr, target)}")

Output:

Index of 6: 2

Result:

Thus the above program was executed successfully


Ex. No: 3(b) Date: 24.09.24

Binary Search

Aim:

To implement a more efficient search method for sorted lists, using divide-and-conquer techniques
to quickly locate an item by repeatedly dividing the search space in half.

Algorithm:

• Define a sorted list arr and an element target.


• Set low to 0 and high to the length of the list minus 1.
• While low <= high, calculate the middle index mid = (low + high) // 2.
• If the element at mid is equal to target, return mid.
• If arr[mid] < target, set low = mid + 1.
• If arr[mid] > target, set high = mid - 1. If no match, return -1.

Program:

def binary_search(arr, target):


arr.sort() # Ensure the array is sorted
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

# Example
arr = [10, 4, 7, 1, 3]
target = 7
print(f"Index of {target}: {binary_search(arr, target)}")

Output:

Index of 7: 2

Result:

Thus the above program was executed successfully.


4. Selection Sort, Insertion Sort

Ex. No: 4(a) Date: 01.10.24

Selection Sort

Aim:

To understand the sorting process by selecting the smallest element in each pass and swapping it
into its correct position, and to practice working with loops and conditional statements.

Algorithm:

• Loop through each element in the list.


• Find the minimum element from the unsorted part of the list.
• Swap the minimum element with the first element of the unsorted part.
• Move the boundary between sorted and unsorted parts.
• Repeat steps 2-4 until the entire list is sorted.
• Return the sorted list.

Program:

def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr

# Example
arr = [64, 34, 25, 12, 22, 11, 90]
print(f"Sorted array: {selection_sort(arr)}")

Output:

Sorted array: [11, 12, 22, 25, 34, 64, 90]

Result:

Thus the above program was executed successfully.


Ex. No: 4(b) Date: 01.10.24

Insertion Sort

Aim:

To practice sorting by gradually building a sorted portion of the list and inserting elements in the
correct position, thereby demonstrating the concept of "insertion" sorting.

Algorithm:

• Start with the second element in the list.


• Compare it with the previous element and shift the elements greater than the current
element one position to the right.
• Insert the current element at the correct position.
• Move to the next element and repeat step 2 until the list is sorted.
• Continue until all elements are sorted.
• Return the sorted list.

Program:

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr

# Example
arr = [64, 34, 25, 12, 22, 11, 90]
print(f"Sorted array: {insertion_sort(arr)}")

Output:

Sorted array: [11, 12, 22, 25, 34, 64, 90]

Result:

Thus the above program was executed successfully.


5. Merge Sort, Quick Sort

Ex. No: 5(a) Date: 08.10.24

Merge Sort

Aim:

To demonstrate the divide-and-conquer approach to sorting by recursively dividing a list and


merging the sorted parts back together efficiently.

Algorithm:

• If the list has more than one element, divide the list into two halves.
• Recursively apply merge sort to each half.
• Merge the two sorted halves into a single sorted list.
• Return the merged list.
• Repeat until all lists are of length 1.
• Combine the sorted lists back into one sorted list.

Program:

def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]

merge_sort(left)
merge_sort(right)

i=j=k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1

while i < len(left):


arr[k] = left[i]
i += 1
k += 1

while j < len(right):


arr[k] = right[j]
j += 1
k += 1
return arr
# Example
arr = [38, 27, 43, 3, 9, 82, 10]
print(f"Sorted array: {merge_sort(arr)}")

Output:

Sorted array: [3, 9, 10, 27, 38, 43, 82]

Result:

Thus the above program was executed successfully.


Ex. No: 5(b) Date: 08.10.24

Quick Sort

Aim:

To implement a recursive sorting algorithm that selects a pivot element and partitions the list into
smaller sublists, using the concept of recursion and partitioning.

Algorithm:

• Choose a pivot element from the list (typically the last element).
• Partition the list into two sublists: elements smaller than the pivot and elements greater than
the pivot.
• Recursively apply quick sort to each sublist.
• Merge the sublists and pivot back into a sorted list.
• Repeat until all sublists are of length 1.
• Return the sorted list.

Program:

def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
less_than_pivot = [x for x in arr[1:] if x <= pivot]
greater_than_pivot = [x for x in arr[1:] if x > pivot]
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)

# Example
arr = [38, 27, 43, 3, 9, 82, 10]
print(f"Sorted array: {quick_sort(arr)}")

Output:

Sorted array: [3, 9, 10, 27, 38, 43, 82]

Result:

Thus the above program was executed successfully.


Ex. No: 6 Date: 22.10.24

6. Implementing Applications Using Lists, Tuples

Aim:
To understand and apply basic data structures like lists and tuples, and practice common operations
like adding, removing, and accessing elements in these structures.

Algorithm:

• Define a list or tuple with elements.


• Perform operations such as appending, removing, or modifying elements in the list.
• For a tuple, since it is immutable, retrieve or access elements but do not modify them.
• Loop through the list or tuple to perform operations (e.g., find a value or count occurrences).
• Use the methods available for lists (e.g., append(), pop(), remove()) or for tuples (e.g.,
count(), index()).
• Return or display the modified list or tuple.

Program:

def list_and_tuple_example():
# List
my_list = [1, 2, 3, 4, 5]
my_list.append(6)

# Tuple
my_tuple = (1, 2, 3, 4, 5)

print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")

list_and_tuple_example()

Output:

List: [1, 2, 3, 4, 5, 6]
Tuple: (1, 2, 3, 4, 5)

Result:

Thus the above program was executed successfully.


Ex. No: 7 Date: 19.11.24

7. Implementing Programs Using Sets, Dictionaries

Aim:

To work with unordered collections of unique elements, applying operations like adding, removing,
and checking membership in a set and dictionary.

Algorithm:

• Define a set or dictionary with initial elements.


• For a set, add elements using add() and remove using remove().
• For a dictionary, use key-value pairs and perform operations like adding or modifying items.
• Check for membership using in for both sets and dictionaries.
• Loop through the set or dictionary to perform specific tasks (e.g., print or search values).
• Return or print the final modified set or dictionary.

Program:

# Creating two sets


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union of two sets


union_set = set1 | set2
print("Union of set1 and set2:", union_set)
# Intersection of two sets
intersection_set = set1 & set2
print("Intersection of set1 and set2:", intersection_set)

# Difference of two sets (set1 - set2)


difference_set = set1 - set2
print("Difference of set1 and set2:", difference_set)

# Subset check (Is set1 a subset of set2?)


is_subset = set1.issubset(set2)
print("Is set1 a subset of set2?", is_subset)

# Adding an element to a set


set1.add(9)
print("Set1 after adding an element:", set1)

# Removing an element from a set


set1.remove(3)
print("Set1 after removing an element:", set1)

# Creating a dictionary
student_grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}

# Accessing values using keys


print("\nAlice's grade:", student_grades["Alice"])
print("Bob's grade:", student_grades["Bob"])

# Adding a new key-value pair


student_grades["David"] = 88
print("Updated student grades:", student_grades)

# Updating the value for an existing key


student_grades["Alice"] = 90
print("Updated Alice's grade:", student_grades["Alice"])

# Deleting a key-value pair


del student_grades["Charlie"]
print("Student grades after deleting Charlie:", student_grades)

# Checking if a key exists


is_bob_exists = "Bob" in student_grades
print("Is Bob in the dictionary?", is_bob_exists)

# Iterating through dictionary


print("\nAll students and their grades:")
for student, grade in student_grades.items():
print(f"{student}: {grade}")

Output:

Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7, 8}


Intersection of set1 and set2: {4, 5}
Difference of set1 and set2: {1, 2}
Is set1 a subset of set2? False
Set1 after adding an element: {1, 2, 4, 5, 9}
Set1 after removing an element: {1, 2, 4, 5, 9}

Alice's grade: 85
Bob's grade: 92
Updated student grades: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
Updated Alice's grade: 90
Student grades after deleting Charlie: {'Alice': 90, 'Bob': 92, 'David': 88}
Is Bob in the dictionary? True

All students and their grades:


Alice: 90
Bob: 92
David: 88

Result:

Thus the above program was executed successfully.


Ex. No: 8 Date: 21.11.24

8. Implementing Programs Using Functions

Aim:
To understand the concept of functions in Python by defining reusable code blocks that take
parameters and return values, enhancing code modularity and clarity.

Algorithm:

• Define a function using the def keyword with necessary parameters.


• Perform the required operations inside the function.
• Use conditionals or loops if necessary to process the input.
• Return the result from the function.
• Call the function with appropriate arguments.
• Display the result of the function call.

Program:

# Function to add two numbers


def add(x, y): return x + y

# Function to subtract two numbers


def subtract(x, y): return x - y

# Function to multiply two numbers


def multiply(x, y): return x * y

# Function to divide two numbers


def divide(x, y): return x / y if y != 0 else "Division by zero error"

# Function to check if a number is prime


def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0: return False
return True

# Function to find factorial


def factorial(n): return 1 if n == 0 else n * factorial(n - 1)

# Function to reverse a string


def reverse_string(s): return s[::-1]

# Function to find max in a list


def find_max(nums): return max(nums)

# Function to calculate average of numbers in a list


def average(nums): return sum(nums) / len(nums) if nums else 0

# Function to remove duplicates from a list


def remove_duplicates(nums): return list(set(nums))

# Main function to test the functions


def main():
print("Addition:", add(5, 3))
print("Prime check:", is_prime(7))
print("Factorial:", factorial(5))
print("Reversed string:", reverse_string("hello"))
print("Max in list:", find_max([1, 2, 3, 4, 5]))
print("Average of list:", average([1, 2, 3, 4, 5]))
print("List without duplicates:", remove_duplicates([1, 2, 2, 3, 4, 4]))

if __name__ == "__main__":
main()

Output:

Addition: 8
Prime check: True
Factorial: 120
Reversed string: olleh
Max in list: 5
Average of list: 3.0
List without duplicates: [1, 2, 3, 4]

Result:

Thus the above program was executed successfully.


Ex. No: 9 Date: 21.11.24

9. Implementing Programs Using Strings

Aim:
To manipulate and work with string data types in Python, using various string methods and
operations to perform transformations and analysis on text data.

Algorithm:

• Define a string variable.


• Use string methods like len(), split(), join(), replace(), etc., to manipulate the string.
• Use slicing to extract substrings.
• Perform conditional checks to find patterns (e.g., check if a string is a palindrome).
• Iterate through the string using loops for specific tasks (e.g., count vowels).
• Return or print the manipulated string.

Program:

Initialize strings
str1, str2 = "Hello", "World"

# Concatenate strings
print("Concatenated:", str1 + " " + str2)

# Repeat string
print("Repeated:", str1 * 3)

# String length
print("Length:", len(str1 + str2))

# Slicing
print("Sliced:", (str1 + str2)[0:5])

# Uppercase and lowercase


print("Upper:", (str1 + str2).upper())
print("Lower:", (str1 + str2).lower())

# Replace a substring
print("Replaced:", (str1 + str2).replace("World", "Universe"))

# Check if substring exists


print("'Hello' in concatenated:", "Hello" in (str1 + str2))

# Split string
print("Split:", (str1 + " " + str2).split())

# String formatting
name, age = "Alice", 25
print(f"Formatted: Hello {name}, you are {age} years old.")

# Strip spaces
print("Stripped:", " Hello World! ".strip())

# Find substring position


print("Position of 'World':", (str1 + str2).find("World"))

Output:

Concatenated: Hello World


Repeated: HelloHelloHello
Length: 10
Sliced: Hello
Upper: HELLOWORLD
Lower: helloworld
Replaced: HelloUniverse
'Hello' in concatenated: True
Split: ['Hello', 'World']
Formatted: Hello Alice, you are 25 years old.
Stripped: Hello World!
Position of 'World': 5

Result:

Thus the above program was executed successfully.


Ex. No: 10 Date: 26.11.24

10. Implementing programs using written modules and Python Standard Libraries

Aim:

To write a python program for Implementing programs using written modules and Python Standard
Libraries (pandas, numpy, Matplotlib, scipy)

Algorithm:

• Import necessary libraries (e.g., import pandas as pd, import numpy as np).
• Create data structures (e.g., DataFrame, numpy arrays).
• Perform the required computations or analysis (e.g., apply functions, perform matrix
operations).
• Use libraries to visualize data (e.g., matplotlib.pyplot to plot graphs).
• Perform any necessary statistical analysis using scipy.
• Return or display results based on the library functions used.

Program:

# Importing necessary libraries


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

# Step 1: Creating a dataset using pandas


data = {
'Height': [160, 170, 175, 180, 185, 190, 195, 200],
'Weight': [55, 65, 70, 75, 80, 85, 90, 95]
}

# Creating a DataFrame
df = pd.DataFrame(data)

# Step 2: Using numpy for numerical operations


mean_height = np.mean(df['Height'])
mean_weight = np.mean(df['Weight'])

print(f"Mean Height: {mean_height}")


print(f"Mean Weight: {mean_weight}")

# Step 3: Plotting a graph using Matplotlib


plt.figure(figsize=(8, 5))
plt.scatter(df['Height'], df['Weight'], color='blue', label='Height vs Weight')
plt.title('Height vs Weight Scatter Plot')
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.legend()
plt.grid(True)
plt.show()
# Step 4: Performing a simple statistical test using scipy
# Perform a Pearson correlation test between Height and Weight
correlation, p_value = stats.pearsonr(df['Height'], df['Weight'])

print(f"Pearson Correlation Coefficient: {correlation}")


print(f"P-value: {p_value}")

# Interpretation of the result


if p_value < 0.05:
print("There is a significant correlation between Height and Weight.")
else:
print("There is no significant correlation between Height and Weight.")

Output:

Mean Height: 177.5


Mean Weight: 75.0

Pearson Correlation Coefficient: 0.9892740323234826


P-value: 0.00011902956234687293
There is a significant correlation between Height and Weight.

Result:

Thus the above program was executed successfully.


Ex. No: 11 Date: 28.11.24

11. File Handling

Aim:
To introduce file input/output operations in Python, enabling reading from and writing to files, which
is fundamental for handling external data in real-world applications.

Algorithm:

• Open a file using open() function (read, write, append).


• Read or write data from/to the file using methods like read(), write(), or writelines().
• If reading, process the data (e.g., store it in a list).
• If writing, ensure the file is in the correct mode (write or append).
• Handle file closing with close() or use with statement to automatically close the file.
• Print the result

Program:

# 1. Writing to a File
with open("example.txt", "w") as file:
file.write("Hello, this is a sample text!\n")
file.write("File handling in Python is easy.\n")

print("Data written to file successfully.")

# 2. Reading from the File


with open("example.txt", "r") as file:
content = file.read() # Read the entire file
print("File Content:")
print(content)

# 3. Appending to the File


with open("example.txt", "a") as file:
file.write("This is additional content appended to the file.\n")

print("Data appended to file successfully.")

# 4. Reading File Line by Line


with open("example.txt", "r") as file:
print("File Content Line by Line:")
for line in file:
print(line.strip()) # strip() removes the newline character

# 5. Checking if the File Exists


import os
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File does not exist.")

# 6. Writing a List to the File


data = ["Python is powerful.\n", "File handling is crucial.\n", "Enjoy coding!\n"]
with open("example.txt", "w") as file:
file.writelines(data) # Write list of strings to the file
print("List written to file.")

# 7. Manually Closing the File


file = open("example.txt", "w")
file.write("Manually closing a file.\n")
file.close() # Explicitly closing the file

print("File closed manually.")

Output:

Data written to file successfully.


File Content:
Hello, this is a sample text!
File handling in Python is easy.

Data appended to file successfully.


File Content Line by Line:
Hello, this is a sample text!
File handling in Python is easy.
This is additional content appended to the file.

File exists.
List written to file.
File closed manually.

Result:

Thus the above program was executed successfully.


Ex. No: 12 Date: 03.12.24

12. Exception Handling

Aim:
To implement error handling in Python programs using try, except, and finally blocks, ensuring that
the program handles exceptions gracefully and continues execution when possible.

Algorithm:

• Begin a try block where you place the code that might raise an exception.
• Use except to catch specific exceptions (e.g., ValueError, ZeroDivisionError).
• Optionally, handle exceptions using else if no exception occurs.
• Use finally to clean up resources (e.g., closing files) regardless of whether an exception
occurred.
• Optionally, raise custom exceptions using raise.
• Display appropriate messages for each case (error or success).

Program:

def divide_numbers(num1, num2):


try:
# Trying to divide the numbers
result = num1 / num2
except ZeroDivisionError:
# Handles division by zero
print("Error: Cannot divide by zero!")
except TypeError:
# Handles wrong data types like strings
print("Error: Both inputs must be numbers!")
else:
# If no exception occurred
print(f"The result of {num1} divided by {num2} is: {result}")
finally:
# This will always run
print("Execution finished.")

# Test cases
divide_numbers(10, 2) # Correct division
print("-" * 40)
divide_numbers(10, 0) # Division by zero
print("-" * 40)
divide_numbers(10, 'a') # Invalid type for division
Output:

The result of 10 divided by 2 is: 5.0


Execution finished.
----------------------------------------
Error: Cannot divide by zero!
Execution finished.
----------------------------------------
Error: Both inputs must be numbers!
Execution finished.

Result:

Thus the above program was executed successfully.


Ex. No: 13 Date: 03.12.24

13. Creating and Instantiating Classes

Aim:
To learn object-oriented programming (OOP) concepts by creating classes and instances (objects),
and to demonstrate how to define properties and behaviors (methods) for objects in Python.

Algorithm:

• Define a class using the class keyword.


• Inside the class, define the __init__ method to initialize attributes.
• Define methods that operate on the class's attributes.
• Create an instance of the class by calling the class name.
• Access and modify attributes using dot notation.
• Call the methods using the instance to perform actions.

Program:

class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def display_info(self):
print(f"Car Info: {self.year} {self.make} {self.model}")

# Create an instance
car1 = Car("Toyota", "Corolla", 2020)
car1.display_info()

Output:

Car Info: 2020 Toyota Corolla

Result:

Thus the above program was executed successfully.

You might also like