Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com Official Telegram Support (@PathubsSupport)
Pathubs

100% Free, Zero-Paywall Tech Career Roadmaps, In-Depth Practical Content, and Live Interactive Virtual Labs for Learners Worldwide.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
RoadmapsProgramming FundamentalsPython (Language Choice)
Python 3.12+ / 3.13 Programming Fundamentals Language Choice Multi-Paradigm Foundations

Python Programming Fundamentals — Syntax, Data Structures, OOP & Core Library

Master the core foundations of Python as your chosen programming language. Learn Python's clean syntax and whitespace indentation rules, variables and dynamic typing, control flow and structural pattern matching (match-case), functions and parameter mechanics, core collections (lists, tuples, dictionaries, sets), robust exception handling, basic OOP classes, file I/O, and the essential standard library.

Category: Programming Fundamentals
Runtime: Python 3.12 / 3.13 (CPython Standard)
Pillars: Syntax • Collections • Functions • OOP • File I/O

Curriculum Outline & Language Map

10 Core Modules
01
Syntax, Indentation & PEP 8
02
Variables, Types & F-Strings
03
Conditions, Loops & Match-Case
04
Functions, *args & **kwargs
05
Lists, Tuples, Dicts & Sets
06
Exception Handling & Custom Errors
07
Basic OOP (Classes & Methods)
08
File I/O & Python Standard Library
09
Interactive Python Lab (3 Exercises)
HOT 🔥
10
Debugging Challenge (6 Scenarios)
TEST 🎯

1. Python Syntax & Indentation Rules

Clean readability by design: code blocks defined by whitespace, not curly braces.

The Zen of Python: Readability Counts

Unlike languages like JavaScript, C++, or Java that use curly braces { } and semicolons ; to demarcate blocks, Python uses significant whitespace. A colon : introduces a new block, and every line inside that block must be indented by exactly 4 spaces.

Python Syntax vs Traditional C-style SyntaxPEP 8 Standard
# ✅ IDIOMATIC PYTHON: Clear, clean, whitespace-delimited
def calculate_discount(price: float, is_member: bool) -> float:
    # 4 spaces indent for function body
    if is_member:
        # 8 spaces indent for conditional block
        discount = price * 0.15
        return price - discount
    
    return price

# Comments start with '#'
# Multi-line docstrings use triple quotes:
"""
This is a module or function docstring explaining intent.
"""

2. Variables, Primitive Data Types & F-Strings

Dynamic typing, explicit type casting, and modern string interpolation.

int & float

count = 42 (arbitrary precision int)
pi = 3.14159 (64-bit IEEE float)
Floor division: 7 // 2 = 3
Exponentiation: 2 ** 8 = 256

str (Strings)

Immutable sequence of Unicode characters.
name = "Python"
name[0] -> "P"
name.upper(), .strip()

bool & NoneType

is_active = True
has_errors = False
result = None (represents absence of value)

Type Casting

int("100") -> 100
float("9.9") -> 9.9
str(250) -> "250"
bool(0) -> False

Modern String Interpolation: F-StringsPython 3.6+ standard
username = "Alex"
score = 87.4567
rank = 3

# F-strings evaluate expressions inline with rich formatting:
print(f"Player: {username.upper()}")
print(f"Final Score: {score:.2f}")           # Formatted to 2 decimal places -> 87.46
print(f"Rank with padding: {rank:03d}")        # Padded with zeros -> 003
print(f"Calculation: 10 * 5 = {10 * 5}")      # Inline arithmetic -> 50

3. Conditions, Loops & Structural Pattern Matching

Directing execution flow with conditionals, iterations, and modern match-case.

Conditionals & Logical Operators

age = 20
has_ticket = True

# Logical operators: and, or, not
if age >= 18 and has_ticket:
    print("Entry granted")
elif age >= 18 and not has_ticket:
    print("Ticket required at box office")
else:
    print("Must be accompanied by adult")

Loops (for, while, enumerate)

# 1. Range loop: 0 to 4
for i in range(5):
    print(i)

# 2. Iterating over list with index:
languages = ["Python", "JavaScript", "Rust"]
for index, lang in enumerate(languages, start=1):
    print(f"{index}: {lang}")
Structural Pattern Matching (PEP 634 / 636)Python 3.10+ match-case statement
def handle_command(command: str | list):
    match command:
        case "quit":
            print("Exiting application...")
        case ["load", filename]:
            print(f"Loading file: {filename}")
        case ["set", key, value]:
            print(f"Setting config: {key} = {value}")
        case _:
            print(f"Unknown command: {command}")

4. Functions, Return Values & *args / **kwargs

Building reusable, modular components with flexible parameter contracts.

Comprehensive Function Signatures in PythonPositional, Default, *args, and **kwargs
# Type hints (PEP 484 / PEP 604) document contracts:
def build_profile(
    name: str,
    email: str,
    tier: str = "Standard",        # Default argument
    *interests: str,               # Variadic positional arguments (*args -> tuple)
    **extra_metadata: any          # Variadic keyword arguments (**kwargs -> dict)
) -> dict:
    return {
        "name": name,
        "email": email,
        "tier": tier,
        "interests": list(interests),
        "metadata": extra_metadata
    }

# Calling with mixed positional, args, and kwargs:
user = build_profile(
    "Samantha", 
    "sam@example.com", 
    "Premium", 
    "AI", "Security", "Python",    # Collected into *interests
    city="Seattle", verified=True   # Collected into **extra_metadata
)

5. Core Collections: Lists, Tuples, Dicts & Sets

Selecting the appropriate data structure for sequencing, lookup, and uniqueness.

Data StructureSyntaxMutabilityOrdering & IndexingCommon Use Case
List[1, 2, 3]MutableOrdered, 0-indexed, sliceableDynamic collections, queues, sorting
Tuple(1, 2, 3)ImmutableOrdered, 0-indexed, unpackableFixed coordinates, record tuples, dict keys
Dictionary{ "key": "val" }MutableKey-value pairs, O(1) hash lookupsStructured entities, lookup tables, JSON mapping
Set{ 1, 2, 3 }MutableUnordered, unique values onlyDeduplication, membership test, set operations (&, |, -)
Comprehensions: Elegant Data TransformationIdiomatic Python mapping & filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension: [expression for item in iterable if condition]
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# -> [4, 16, 36, 64, 100]

# Dictionary comprehension: {key: value for item in iterable}
names = ["alice", "bob", "charlie"]
name_lengths = {name: len(name) for name in names}
# -> {'alice': 5, 'bob': 3, 'charlie': 7}

6. Exception Handling & Custom Errors

Gracefully recovering from runtime failures using try, except, else, and finally.

Complete Try / Except / Else / Finally BlockRobust Error Management
# Defining a custom exception inheriting from built-in Exception:
class NegativeValueError(Exception):
    """Raised when an unexpected negative number is supplied."""
    pass

def process_payment(amount: float) -> str:
    try:
        if amount < 0:
            raise NegativeValueError("Amount cannot be negative!")
        fee = 50.0 / amount
    except ZeroDivisionError as err:
        return f"Caught error: Amount cannot be zero ({err})"
    except NegativeValueError as err:
        return f"Validation error: {err}"
    except Exception as err:
        return f"Unexpected fallback error: {err}"
    else:
        # Runs ONLY if no exception was raised in the try block
        return f"Success! Fee: {fee:.2f}"
    finally:
        # Runs ALWAYS (for cleanup, releasing resources)
        print("Payment processing transaction logged.")

7. Basic Object-Oriented Programming (OOP)

Encapsulating state and behavior into reusable classes with __init__ and methods.

Class Blueprint, Constructor & Instance MethodsEncapsulation in Python
class InventoryItem:
    # Class attribute (shared by all instances)
    category = "General Goods"

    # Constructor method initializes instance attributes:
    def __init__(self, sku: str, name: str, price: float, stock: int = 0):
        self.sku = sku
        self.name = name
        self.price = price
        self.stock = stock

    # Instance method (must accept 'self' as first parameter)
    def purchase(self, quantity: int) -> float:
        if quantity > self.stock:
            raise ValueError(f"Insufficient stock for {self.name} (Available: {self.stock})")
        self.stock -= quantity
        return self.price * quantity

    # String representation for printing and debugging:
    def __str__(self) -> str:
        return f"{self.name} [SKU: {self.sku}] - ${self.price:.2f} ({self.stock} in stock)"

item = InventoryItem("SKU-101", "Mechanical Keyboard", 89.99, stock=15)
print(item)  # Calls __str__

8. File I/O & The Python Standard Library

Safely streaming files with context managers and utilizing Python's built-in batteries.

Safe File Reading & Writing

# 1. Writing to a file (overwrites or creates):
with open("report.txt", "w", encoding="utf-8") as f:
    f.write("Line 1: System Online\n")
    f.write("Line 2: All tests passed\n")

# 2. Reading line-by-line (memory-efficient):
with open("report.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Essential Standard Library Modules

import math
import random
import datetime
import json
from pathlib import Path

# Math & Random
sqrt_val = math.sqrt(144)         # 12.0
choice = random.choice(["A", "B"])

# Datetime & JSON
now = datetime.datetime.now()
serialized = json.dumps({"timestamp": str(now)})

9. Interactive Python Coding Labs (3 Executable Exercises)

Write and modify real Python code. Test syntax, collections, OOP, and exceptions with immediate feedback!

grade_evaluator.py
Python Source EditorUTF-8 • Tab Size: 4
Terminal Output & Assertions🔴 TESTS PENDING
Python 3.12.5 (CPython interactive runner)
Programming Fundamentals Test Suite ready.
Select a lab, edit the code, and click "Run / Test".

10. Python Debugging Challenge & Core Pillars Recap

Diagnose 6 authentic bugs encountered by developers learning Python.

1. The Tab vs Space IndentationErrorSyntax Error

Python uses whitespace indentation to define code blocks (functions, loops, conditions). Mixing tabs and spaces in the same file or block causes `TabError` or `IndentationError`. PEP 8 strictly mandates using 4 spaces per indentation level.

Problematic Code SnippetSyntax & Layout
def calculate_average(scores):
    total = sum(scores)
	count = len(scores)  # ⚠️ Mixed Tab character with 4 spaces!
    return total / count
Traceback / Observed Failure:
TabError: inconsistent use of tabs and spaces in indentation
File "math_utils.py", line 3
  count = len(scores)
      ^

What is the correct root-cause fix?

Configure your editor to convert Tabs into 4 spaces, ensuring uniform indentation.
Surround the function body with curly braces { } like in C++ or JavaScript.
Add a semicolon at the end of each line.

Mini Challenge: Choose the Right Collection

You need to store an active collection of 100,000 unique user IDs and perform millisecond membership checks (if user_id in collection:). Which data structure should you use?

A Python set (e.g. user_ids = set()), which provides average O(1) constant-time hash lookups.
A Python list (e.g. user_ids = []), which performs an O(N) linear scan through all 100,000 items.
A Python tuple (e.g. user_ids = ()).

Core Pillars of Python Programming Fundamentals

1. Readability & Indentation
Use 4 spaces for indentation. Consistent whitespace is part of Python's syntax grammar.
2. Strong Dynamic Typing
Variables do not require explicit type declarations, but types are strongly checked. Use f-strings for string interpolation.
3. Idiomatic Control Flow
Master for ... in, enumerate(), and Python 3.10+ match-case for expressive data handling.
4. Right Tool Collections
Use Lists for sequences, Tuples for immutability, Dicts for key-value lookups, and Sets for uniqueness.
5. Error Boundaries
EAFP (Easier to Ask for Forgiveness than Permission): Use try/except blocks to handle edge cases cleanly.
6. Context Managers (with)
Always access external files and system resources using with open(...) as f: to prevent leaks.