Python Advanced & Data Science

Interactive Reference & Exam Portal

Part 1: Advanced Object-Oriented Programming

Encapsulation & Protection Mechanics

  • Public Scope: Attributes without underscores (e.g., self.title). Fully accessible externally; use only when properties have zero input constraints.
  • Private Scope & Name Mangling: Prefixed with double underscores (e.g., self.__height). Python automatically changes the name to _ClassName__attribute behind the scenes to shield parameters from accidental overrides inside inheritance loops.
  • Protected Scope: Prefixed with a single underscore (e.g., self._height). An explicit design/API convention signaling that the layout is internal and subject to change.
class Wall:
    def __init__(self, height):
        self._height = height          # Protected state variable convention
        self.__internal_id = 1024      # Private field; name-mangled to _Wall__internal_id

    def get_height(self):
        return self._height            # Public exposure reader method

Smart Control Properties

class Book:
    def __init__(self, title, isbn):
        self.title = title             # Routes immediately into property setter validation block
        self._isbn = isbn

    @property
    def title(self):
        return self._title             # Safe read lookup (Getter)

    @title.setter
    def title(self, value):
        if not value or not isinstance(value, str):
            raise RuntimeError("Validation Error: Title must be a non-empty text string.")
        self._title = value            # Save state check (Setter)

    @property
    def isbn(self):
        return self._isbn              # Read-only attribute pattern template

Finite Memory Processing

  • Iterables: Common data structure collections (Lists, Tuples, Dictionaries, Sets, Strings) that natively support loop traversal protocols.
  • Generators: Functions implementing evaluation lazily via yield expressions. Streams elements one-by-one, holding execution in place. Exam Catch: Once drained, they are spent and must be re-instantiated.
  • Generator Expressions: Lazy elements wrapped inside parentheses: (expr for x in xs). Keeps memory footprint at O(1).
def languages():
    yield "Python"
    yield "Java"
    yield "Haskell"

# Optimized: Progressively streams scalar fields through open computing parameters
lowest_weight_fast = min(person.weight for person in people)
total_cost = sum(item.price for item in shopping_basket)

Part 2: Regular Expressions (re) Blueprint

Pattern Structural Match Expression
.Any character slot save for explicit newline boundaries
\dDecimal digits matching base layouts [0-9]
\wAlphanumeric words plus underscores [a-zA-Z0-9_]
\sWhitespace character matches (spaces, tabs, newlines)
* / +0+ continuous repetitions / 1+ continuous repetitions
?Zero or one optional match instance
{n,m}Bounded interval loop; matches n to m instances
^ / $Forces strict pattern alignment to start/end of text strings
import re
# Strip formatting characters out of numeric strings using regex
clean_isbn = re.sub(r'[-\s]', '', '978-1779501127') # Output: '9781779501127'

Part 3: Pytest Software Testing Ecosystem

Arrange-Act-Assert (AAA)

def test_task_becomes_overdue():
    # 1. Arrange: Setup objects, data properties, and stub environments
    today = date(2000, 1, 1)
    calendar = CalendarStub(today)
    task = Task('Bake exam cake', date(2000, 1, 2))
    sut = TaskList(calendar) # SUT (System Under Test)
    sut.add_task(task)
    
    # 2. Act: Trigger state mutations inside framework tracking path
    calendar.today = date(2000, 1, 8)
    
    # 3. Assert: Verify metrics cleanly
    assert [task] == sut.overdue_tasks

Fixtures & Numerical Tolerance Limits

  • Use @pytest.mark.parametrize to isolate datasets and avoid cascading test failures.
  • Binary floating-point numbers can introduce minor precision errors (e.g., 0.1 + 0.2 != 0.3). Wrap lookups in pytest.approx().
from pytest import approx
import pytest

def test_floating_point_precision_tolerances():
    assert approx(0.1 + 0.2) == 0.3

def test_creation_with_invalid_title_throws_runtime_error():
    with pytest.raises(RuntimeError):
        Book(title=' ', isbn='978-1779501127')
EXAM WARNING (Production Optimization Strip Trap):
Performance optimization flags (python -O) automatically remove inline assertions from compiled bytecode. Never use raw internal asserts to enforce data validation!

Part 4: Complete Home Automation Exam Scenario

An exhaustive system architecture utilizing Abstract Base Classes (ABC), rich comparisons, device validation (Lamp, Heating, Washing Machine), and automated central tracking engines.

from abc import ABC, abstractmethod

class Device(ABC):
    def __init__(self, name, location, energy_consumption):
        self._name = name
        self._location = location
        self._energy_consumption = energy_consumption

    @property
    def energy_consumption(self): return self._energy_consumption

    def __lt__(self, other): return self.energy_consumption < other.energy_consumption
    def __gt__(self, other): return self.energy_consumption > other.energy_consumption

Part 5: Data Manipulation (Pandas)

Initialization, Slicing, & Mutations

import pandas as pd
import numpy as np

my_series = pd.Series([10, 100, 10], index=['London', 'Tripoli', 'Cairo'])

df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Salary': [60000, 75000, 80000]
})

# Boolean Mask Combining (Always use bitwise operators & or | with round brackets)
london_high_earners = df[(df['Salary'] > 65000) & (df['City'] == 'London')]

Transformations: .apply() & .explode()

  • .apply(axis=1): Custom parsing row-by-row.
  • .explode(): Flattens cells containing lists or strings into separate independent rows.

Part 6: Visualizations (Matplotlib)

Unaligned Bar Chart Blueprint

bar_width = 0.2
x_positions = range(len(df['year']))

plt.figure(figsize=(10, 6))
plt.bar([pos - bar_width for pos in x_positions], df['Pigeons'], bar_width, color='blue', label='Pigeons')
plt.bar(x_positions, df['Sparrows'], bar_width, color='green', label='Sparrows')
plt.xticks(x_positions, df['year'])
plt.legend()
plt.show()

💬 Offline Questions & Q&A

Click on a question to reveal the exam-focused answer.

Q1: What is name mangling in Python, and why does it occur?
Attributes prefixed with double underscores (e.g., self.__height) trigger a compiler transformation that changes the internal slot handle to _ClassName__attribute. This protects internal mechanics against accidental overrides during class inheritance loops.
Q2: What happens if a generator is "spent" during program execution?
Once a generator loop finishes, it is "spent" and empty. Any subsequent loop or lookup over the same generator object will sink silently without raising an error but yielding no items. You must re-instantiate the generator to traverse it again.
Q3: Why shouldn't you use code assertions to enforce business input boundaries?
Production interpreters run with optimization flags (python -O) automatically eliminate inline assert statements from compiled bytecode, which would disable your validation checks in production. Always use explicit conditional exceptions (like if/raise) for business logic.
Q4: What is the difference between .apply() and .explode() in Pandas?
.apply(axis=1) passes user-defined functions across row-by-row matrix tracks, whereas .explode() takes cells with collections (lists/strings) and flattens them into independent structural rows while duplicating the corresponding index handles.