0% found this document useful (0 votes)
28 views8 pages

Module 2 - Part 2.Ipynb - Colab

Uploaded by

harshawaste12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views8 pages

Module 2 - Part 2.Ipynb - Colab

Uploaded by

harshawaste12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

12/3/24, 10:54 PM Module 2 - Part 2.

ipynb - Colab

keyboard_arrow_down Abstract Methods and Abstract Classes in Python


Abstract Class:

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.

keyboard_arrow_down Real-World Example: Abstract Class and Abstract Method

Scenario: Abstract class for Payment system (like Credit Card, PayPal, and Bank Transfer)

from abc import ABC, abstractmethod

# Abstract Class
class Payment(ABC):
@abstractmethod
def pay(self, amount):
"""Abstract method to process payment"""
pass

# Concrete class for Credit Card Payment


class CreditCardPayment(Payment):
def pay(self, amount):
print(f"Processing credit card payment of Rs{amount}")

# Concrete class for UPI Payment


class UPIPayment(Payment):
def pay(self, amount):
print(f"Processing UPI payment of Rs{amount}")

# Concrete class for netbanking Payment


class NetBankingPayment(Payment):
def pay(self, amount):
print(f"Processing Netbanking payment of Rs{amount}")

# Usage
def process_payment(payment_method, amount):
payment_method.pay(amount)

# Instantiate concrete classes and process payment


credit_card = CreditCardPayment()
upi = UPIPayment()
netbanking = NetBankingPayment()

process_payment(credit_card, 100)
process_payment(upi, 200)
process_payment(netbanking, 300)

Processing credit card payment of Rs100


Processing UPI payment of Rs200
Processing Netbanking payment of Rs300

keyboard_arrow_down Real-World Example 2: program illustrating the use of abstract classes and abstract methods using the abc module:

Scenario: Abstract Class for Shapes

from abc import ABC, abstractmethod

# Abstract base class


class Shape(ABC):
@abstractmethod
def calculate_area(self):
"""Abstract method to calculate area"""
pass

@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

# Concrete class for Circle


class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def calculate_area(self):
return 3.14 * self.radius ** 2

def calculate_perimeter(self):
return 2 * 3.14 * self.radius

# Concrete class for Rectangle


class Rectangle(Shape):
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth

def calculate_area(self):
return self.length * self.breadth

def calculate_perimeter(self):
return 2 * (self.length + self.breadth)

# Example usage

shapes = [Circle(5), Rectangle(4, 6)]

for shape in shapes:


print(f"Area: {shape.calculate_area()}")
print(f"Perimeter: {shape.calculate_perimeter()}")

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

keyboard_arrow_down Real-World Example 3: Abstract Class for Employees

This example demonstrates polymorphism where different employee types calculate their salaries differently, but the interface ( get_salary() )
remains consistent.

from abc import ABC, abstractmethod

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)]

for emp in employees:


print(f"Salary: {emp.get_salary()}")

Salary: 50000
Salary: 2400

keyboard_arrow_down Interfaces in Python


Python does not have a keyword for defining interfaces like some other programming languages. Instead, abstract classes are
used to achieve the same functionality. Abstract classes with only abstract methods act as interfaces.

keyboard_arrow_down Real-World Example: Interface

Scenario: A Shape interface where different shapes (like Circle and Rectangle) implement a calculate_area() method

from abc import ABC, abstractmethod

# Interface (Abstract Class with only abstract methods)


class Shape(ABC):
@abstractmethod
def calculate_area(self):
"""Abstract method to calculate area"""
pass

# Concrete class for Circle


class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def calculate_area(self):
return 3.14 * self.radius * self.radius

# Concrete class for Rectangle


class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def calculate_area(self):
return self.width * self.height

# Usage
shapes = [Circle(5), Rectangle(4, 6)]

for shape in shapes:


print(f"Area: {shape.calculate_area()}")

Area: 78.5
Area: 24

keyboard_arrow_down Key Points:


1. Abstract classes in Python are defined using the ABC class.
2. Abstract methods are declared with the @abstractmethod decorator.
3. Concrete subclasses must implement all abstract methods of their parent class.
4. Abstract classes with only abstract methods can be used as interfaces.

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

keyboard_arrow_down Compile-time , Runtime and Logical errors


In Python, errors are typically classified into three main categories: compile-time errors, runtime errors, and logical errors. Each type of error
occurs at different stages of code execution and has different causes. Understanding these errors is important for writing robust code and for
effective debugging.

keyboard_arrow_down 1. Compile-time Errors (Syntax Errors)


Definition: Compile-time errors (also called syntax errors) occur when the Python interpreter encounters code that doesn't conform to the
syntax rules of the language. These errors are detected before the program starts executing, during the process of parsing the code.

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:

# SyntaxError example: missing closing parenthesis


print("Hello, World!" # This will cause a compile-time error

# Output:
# SyntaxError: unexpected EOF while parsing

# SyntaxError example: incorrect indentation


def greet():
print("Hello")
print("World") # IndentationError: unexpected indent

# Output:
# IndentationError: unexpected indent

File "<ipython-input-1-374c4defcad8>", line 2


print("Hello, World!" # This will cause a compile-time error
^
SyntaxError: '(' was never closed

Next steps: Fix error

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.

keyboard_arrow_down 2. Runtime Errors (Exceptions)


Definition: Runtime errors (also called exceptions) occur while the program is running, after it has successfully passed the compilation
phase. These errors happen when the code encounters an unexpected situation during execution that prevents it from continuing.

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.).

Cause: Runtime errors are typically caused by:

Invalid operations (e.g., dividing by zero).


Using a variable before it's initialized.
Incorrect data types or operations that are not allowed between incompatible types (e.g., trying to add a string and an integer).
Accessing elements that don't exist (e.g., index out of bounds for a list).
File operations, such as trying to open a non-existent file.

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:

ZeroDivisionError: division by zero

Next steps: Explain error

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.

# Handling ZeroDivisionError with try-except


try:
result = x / y
except ZeroDivisionError:
print("Error: Cannot divide by zero.")

Error: Cannot divide by zero.

keyboard_arrow_down 3. Logical Errors


Definition: Logical errors are mistakes in the program's logic that cause the program to behave incorrectly or produce the wrong output.
These errors do not produce any syntax or runtime errors, but they lead to incorrect results or behavior.

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:

Incorrect mathematical calculations or formulas.


Wrong conditions in if or while statements.
Using the wrong variable or making an incorrect assumption about how something should work.

Example:

# Incorrect result due to a logical error in the program


def calculate_average(a, b):
return a + b / 2 # This is wrong; it should be (a + b) / 2

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:

Carefully review and debug the logic of your program.


Use print statements or debugging tools to track the flow of the program and check intermediate results.
Test the program with different inputs to ensure it behaves as expected.
Consider using unit tests to validate that your functions return the expected outputs.

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

Key Differences Between the Three Types of Errors


Error Type Occurrence Time Cause Example How to Fix

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.

keyboard_arrow_down Exceptions and Exception Handling


In Python, exceptions are errors that occur during the execution of a program. When an exception occurs, the normal flow of the program is
disrupted, and the interpreter searches for an appropriate way to handle it. If it finds none, the program stops and an error message is
displayed. Exception handling allows you to manage these errors gracefully without crashing the program.

keyboard_arrow_down Exception Handling


Python uses try , except , else , and finally blocks to handle exceptions:

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.")

keyboard_arrow_down Types of Exceptions


Python has a variety of built-in exceptions. Some common ones include:

1. ArithmeticError: Base class for all arithmetic errors, including:

ZeroDivisionError: Occurs when dividing by zero.


OverflowError: Raised when a calculation exceeds the maximum limit for a numeric type.

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.

5. TypeError: Occurs when an operation or function is applied to an object of inappropriate type.

6. FileNotFoundError: Raised when attempting to open a file that doesn’t exist.

7. ImportError: Occurs when an import statement fails to find the specified module.

8. AttributeError: Raised when an invalid attribute is accessed for an object.

9. IOError: Raised for input/output operations failure (e.g., when a file cannot be opened).

10. AssertionError: Raised when an assertion statement fails.

'''
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:

def print_exceptions(cls, indent=0):


print(" " * indent + cls.__name__)
for subclass in cls.__subclasses__():
print_exceptions(subclass, indent + 2)

print("List of all built-in exceptions in Python:")


print_exceptions(BaseException)

keyboard_arrow_down Custom Exceptions


In addition to built-in exceptions, Python allows you to define custom exceptions by creating new exception classes. This is useful when you
want to handle specific error cases in your program that are not covered by the built-in exceptions.

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

You might also like