Module 2 - Part 2.Ipynb - Colab
Module 2 - Part 2.Ipynb - Colab
ipynb - Colab
An abstract class is a class that contains one or more abstract methods. It cannot be instantiated directly. Abstract classes are used to define a
blueprint for other classes. They are created using the ABC module ( from abc import ABC, abstractmethod ).
Abstract Method:
An abstract method is a method that is declared but not implemented. Any concrete subclass inheriting from an abstract class must implement
all its abstract methods unless the subclass itself is also abstract.
Scenario: Abstract class for Payment system (like Credit Card, PayPal, and Bank Transfer)
# Abstract Class
class Payment(ABC):
@abstractmethod
def pay(self, amount):
"""Abstract method to process payment"""
pass
# Usage
def process_payment(payment_method, amount):
payment_method.pay(amount)
process_payment(credit_card, 100)
process_payment(upi, 200)
process_payment(netbanking, 300)
keyboard_arrow_down Real-World Example 2: program illustrating the use of abstract classes and abstract methods using the abc module:
@abstractmethod
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 1/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
def calculate_perimeter(self):
"""Abstract method to calculate perimeter"""
pass
def calculate_area(self):
return 3.14 * self.radius ** 2
def calculate_perimeter(self):
return 2 * 3.14 * self.radius
def calculate_area(self):
return self.length * self.breadth
def calculate_perimeter(self):
return 2 * (self.length + self.breadth)
# Example usage
Area: 78.5
Perimeter: 31.400000000000002
Area: 24
Perimeter: 20
Area: 78.5
Perimeter: 31.400000000000002
Area: 24
Perimeter: 20
circ1 = Circle(5)
Rect1 = Rectangle(4,6)
print(circ1.calculate_area())
print(circ1.calculate_perimeter())
print(Rect1.calculate_area())
print(Rect1.calculate_perimeter())
78.5
31.400000000000002
24
20
This example demonstrates polymorphism where different employee types calculate their salaries differently, but the interface ( get_salary() )
remains consistent.
class Employee(ABC):
@abstractmethod
def get_salary(self):
"""Abstract method to get salary"""
pass
@staticmethod
def get_sum(a,b):
return a+b
class FullTimeEmployee(Employee):
def __init__(self, salary):
self.salary = salary
def get_salary(self):
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 2/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
return self.salary
class PartTimeEmployee(Employee):
def __init__(self, hourly_rate, hours_worked):
self.hourly_rate = hourly_rate
self.hours_worked = hours_worked
def get_salary(self):
return self.hourly_rate * self.hours_worked
# Example usage
employees = [FullTimeEmployee(50000), PartTimeEmployee(20, 120)]
Salary: 50000
Salary: 2400
Scenario: A Shape interface where different shapes (like Circle and Rectangle) implement a calculate_area() method
def calculate_area(self):
return 3.14 * self.radius * self.radius
def calculate_area(self):
return self.width * self.height
# Usage
shapes = [Circle(5), Rectangle(4, 6)]
Area: 78.5
Area: 24
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 3/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
When do they occur?: During the parsing phase when the code is being compiled into bytecode, but before execution begins.
Cause: These errors are typically caused by typos, missing punctuation, or incorrect usage of Python's syntax (e.g., forgetting a colon after
an if statement, using an incorrect indentation level, or misspelling a keyword).
Example:
# Output:
# SyntaxError: unexpected EOF while parsing
# Output:
# IndentationError: unexpected indent
How to fix:
Ensure that all parentheses, brackets, and braces are properly closed.
Check for proper indentation.
Use correct Python syntax for constructs like if , for , while , def , etc.
When do they occur?: During the execution of the program, when certain conditions or operations lead to errors (like division by zero,
invalid input, file not found, etc.).
Example:
# ZeroDivisionError example
x = 10
y = 0
print(x / y) # This will cause a runtime error (division by zero)
# Output:
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 4/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
# ZeroDivisionError: division by zero
# FileNotFoundError example
with open("non_existent_file.txt", "r") as f:
content = f.read() # This will cause a runtime error (file not found)
# Output:
# FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.txt'
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-a68bce745c2d> in <cell line: 4>()
2 x = 10
3 y = 0
----> 4 print(x / y) # This will cause a runtime error (division by zero)
5
6 # Output:
How to fix:
Add error handling using try ... except blocks to handle potential exceptions.
Ensure that operations like division or file access are only performed under valid conditions.
Use checks (e.g., if statements) to ensure data is in the correct format before performing operations.
When do they occur?: Logical errors are usually detected during the execution of the program, but they do not trigger exceptions or
crashes. The program runs normally but produces incorrect results or behaves in unintended ways.
Cause: Logical errors typically occur when the program's logic is flawed. For example:
Example:
result = calculate_average(4, 6)
print(result) # Output will be 7.0, but the correct average should be 5.0
7.0
In this example, the logical error is caused by operator precedence. The expression a + b / 2 is interpreted as a + (b / 2) due to operator
precedence, which gives the wrong result. The correct calculation should be (a + b) / 2 .
How to fix:
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 5/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
# Correct version of the function
def calculate_average(a, b):
return (a + b) / 2
result = calculate_average(4, 6)
print(result) # Output: 5.0
Compile-time Before execution Syntax issues or missing components SyntaxError, IndentationError Correct the syntax, indentation, or structure
Runtime During execution Invalid operations or external conditions (e.g., file not found) ZeroDivisionError, FileNotFoundError Use try ... except blocks for error handling
Logical During execution Incorrect logic or algorithm Incorrect results, wrong output Debug the logic and test with different cases
Key Points
Compile-time errors (syntax errors) prevent the program from starting because the Python interpreter cannot understand the code due to
incorrect syntax or structure.
Runtime errors (exceptions) occur during execution, often due to invalid operations, incorrect input, or missing resources.
Logical errors are the hardest to detect because the code runs without crashing but produces incorrect results due to flawed logic or
assumptions.
Understanding these different types of errors is crucial for debugging and improving the reliability of Python programs. To minimize errors, use
clear and correct syntax, handle potential exceptions, and thoroughly test the logic of your program.
1. try block: The code that may raise an exception is placed inside this block.
2. except block: If an exception occurs in the try block, it is caught here. You can specify the exception type to catch specific errors.
3. else block (optional): Executed if no exception occurs in the try block.
4. finally block (optional): Always executed, regardless of whether an exception occurred or not. Useful for cleanup code.
Example:
try:
numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input; please enter a number.")
else:
print("Result:", result)
finally:
print("Execution complete.")
2. IndexError: Occurs when trying to access an index that is out of range in a list or tuple.
3. KeyError: Raised when trying to access a dictionary key that doesn’t exist.
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 6/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
4. ValueError: Raised when an operation receives an argument of the correct type but with an inappropriate value.
7. ImportError: Occurs when an import statement fails to find the specified module.
9. IOError: Raised for input/output operations failure (e.g., when a file cannot be opened).
'''
You can print all the built-in exceptions in Python by accessing the __bases__ attribute of the BaseException class.
This class is the base for all built-in exceptions in Python.
You can retrieve and print all built-in exceptions by using the subclasses() method.
'''
#Here’s a simple script to print all built-in exceptions in Python:
Example
class NegativeNumberError(Exception):
"""Raised when a negative number is encountered."""
pass
class ExitProgram(Exception):
"""Raised when a positive number is encountered."""
pass
try:
num = int(input("Enter a positive number: "))
if num < 0:
raise NegativeNumberError("Only positive numbers are allowed.")
else:
raise ExitProgram("Program terminated")
except NegativeNumberError as e:
print(e)
print("Program terminated.")
except ExitProgram as e:
print(e)
Key Points
Using exception handling ensures that your program can gracefully manage errors and continue running without crashing abruptly.
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 7/8
12/3/24, 10:54 PM Module 2 - Part 2.ipynb - Colab
Could not connect to the reCAPTCHA service. Please check your internet connection and reload to get a reCAPTCHA challenge.
https://colab.research.google.com/drive/1p9sq8stSp38jHtsA0OSmWRbKHyftVvZA#scrollTo=Tayc5ptRwNWm&printMode=true 8/8