←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Revision

Python Programming · Unit 4 Revision

Quick summary and key points for Unit 4

Procedural vs OOP, Classes, Objects, Encapsulation & Abstraction

Overview: A procedural fee calculator might pass a balance between several functions.

Procedural vs Object-Oriented Programming (OOP)

  • Basic Unit: Program is divided into small Functions / Procedures
  • Focus: Focuses on “How to do” (Algorithm / Sequence of steps)
  • Data & Functions: Data and functions are separate; global data moves freely between functions
  • Data Security: Low Security: Any function can accidentally modify global data
  • Approach: Follows a Top-Down approach
  • Code Reusability: Limited to calling existing functions

Classes, Objects, __init__() Constructor & self

  • Class: A logical blueprint or template for creating objects.
  • Object: A real-world instance of a class that occupies memory.
  • __init__() Method (Constructor): A special magic method that runs automatically whenever a new object of the class is created, used to initialize object…
  • self Keyword: Refers to the current object instance calling the method (similar to this in C++/Java).

View diagram · The 4 Pillars (Principles) of OOP in Python

Principle 1: Encapsulation & Data Hiding

  • Encapsulation is the process of binding data (variables) and the methods (functions) that operate on that data into a single unit…
  • Access Specifiers in Python (Public, Protected, Private): Unlike Java/C++, Python does not use public, protected, or private keywords.
  • 1. Public: self.name (No underscore)
  • 2. Protected: self._salary (Single underscore _)
  • 3. Private: self.__balance (Double underscore __)

Principle 2: Abstraction in Python

  • Abstraction means hiding complex internal implementation details from the user and exposing only the necessary functionality (interface).
  • Real-World Example: When you press the brake pedal in a car, the car stops.
  • How to Achieve Abstraction in Python (abc Module): Python provides the built-in abc (Abstract Base Classes) module.
  • A class that inherits from ABC and contains at least one @abstractmethod is called an Abstract Class.
  • You cannot create an object of an Abstract Class directly; child classes must implement its abstract methods.

Inheritance, Polymorphism & Inner Classes in Python

Overview: A ScholarshipStudent can reuse Student details while overriding a fee calculation.

Principle 3: Inheritance in Python

  • Inheritance is the mechanism by which a new class (Child / Derived / Subclass) acquires all the attributes and methods of an existing…
  • Main Benefit: Code Reusability — write common code once in the Parent class and reuse it across multiple Child classes!
  • Syntax of Inheritance in Python: Instead of keywords like extends (in Java), Python passes the Parent class inside parentheses ( ):
  • Types of Inheritance in Python: Unlike Java, Python directly supports Multiple Inheritance using classes!

View diagram · 5 Types of Inheritance Supported in Python

Principle 4: Polymorphism in Python

  • The word Polymorphism comes from Greek (Poly = Many, Morphs = Forms).
  • A. Built-in Polymorphism (Operator & Function Overloading): The + operator performs arithmetic addition for numbers (10 + 20 = 30), but performs concatenation for strings (`“Hello “ +…
  • The len() function counts characters in a string (len("BCA") = 3), items in a list (len([10, 20]) = 2), or keys in a dictionary.
  • B. Method Overriding (Runtime Polymorphism): When a Child class provides its own specific implementation of a method that is already defined in its Parent class, it…

Inner Classes (Nested Classes) in Python

  • An Inner Class (or Nested Class) is a class defined entirely inside the body of another class (the Outer Class).
  • Why Use Inner Classes?: Logical Grouping: When one class is tightly coupled with another class and has no meaning outside it (for example, a Laptop class having an…
  • Better Encapsulation & Organization: Keeps helper classes hidden inside the main outer class.

Exception Handling: Errors, try-except-finally, raise & Custom Exceptions

Overview: If a mark is entered as abc, int raises ValueError.

Types of Errors in Python

  • Errors in a computer program are classified into three categories:
  • 1. Syntax Errors (Compile-Time): Before execution (during parsing)
  • 2. Logical Errors: During execution
  • 3. Exceptions (Runtime Errors): During execution (at runtime)
  • Common Built-in Exceptions in Python: ZeroDivisionError: Dividing a number by 0 (10 / 0).
  • ValueError: Passing an invalid value to a function (int("abc")).
  • TypeError: Performing an operation on incompatible types ("Age: " + 20).
  • IndexError: Accessing a list index that is out of range (L[99]).

Exception Handling Blocks: try, except, else, finally

  • An exception in try transfers control to a matching except clause.

View diagram · Flow of try - except - else - finally in Python

Raising Exceptions Explicitly (raise Keyword)

  • Sometimes, you want to manually trigger (throw) an exception in your code when a business rule is violated.

Need for Custom (User-Defined) Exceptions & Case Study

  • Why Do We Need Custom Exceptions?: Python’s built-in exceptions (ZeroDivisionError, ValueError, IndexError) only cover technical programming errors.
  • A bank ATM rejecting a withdrawal if the balance drops below Rs.
  • An online exam portal rejecting registration if a student’s age is below 17 (UnderAgeCandidateError).
  • Case Study: ATM Banking Withdrawal with Custom Exception: Let’s create a user-defined exception class called InsufficientFundsError by inheriting from the built-in Exception…

Regular Expressions (Regex) in Python (re Module)

Overview: To validate a six-digit PIN code field, use a whole-string match with [0-9]{6}.

Core Functions in the re Module

  • The re module provides 5 main functions for pattern matching:
  • Difference between re.match() and re.search():
    • re.match() checks only at the start of the string.
    • re.search() searches anywhere inside the entire string.

View diagram · Top Functions in Python’s re Module

RegEx Meta-Characters & Special Sequences

  • To build powerful search patterns, RegEx uses Meta-characters and Special Sequences (always prefix regex strings with r"..." for Raw…
  • [ ]: A set/range of characters
  • ^: Starts with
  • .: Any single character (except newline)
  • *: 0 or more occurrences
  • +: 1 or more occurrences
  • ?: 0 or 1 occurrence (Optional)
  • \d: Matches any Digit (0 to 9)

Practical Exam Case Studies (Validation Programs)

  • Case Study 1: Validate an Indian 10-Digit Mobile Number: An Indian mobile number must start with 6, 7, 8, or 9 followed by 9 more digits (total 10 digits):
  • Pattern: r"^[6-9]\d{9}\Z"