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.
Clean readability by design: code blocks defined by whitespace, not curly braces.
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.
# ✅ 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.
"""Dynamic typing, explicit type casting, and modern string interpolation.
count = 42 (arbitrary precision int)pi = 3.14159 (64-bit IEEE float)
Floor division: 7 // 2 = 3
Exponentiation: 2 ** 8 = 256
Immutable sequence of Unicode characters.name = "Python"name[0] -> "P"name.upper(), .strip()
is_active = Truehas_errors = Falseresult = None (represents absence of value)
int("100") -> 100float("9.9") -> 9.9str(250) -> "250"bool(0) -> False
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 -> 50Directing execution flow with conditionals, iterations, and modern match-case.
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")# 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}")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}")Building reusable, modular components with flexible parameter contracts.
# 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
)Selecting the appropriate data structure for sequencing, lookup, and uniqueness.
| Data Structure | Syntax | Mutability | Ordering & Indexing | Common Use Case |
|---|---|---|---|---|
| List | [1, 2, 3] | Mutable | Ordered, 0-indexed, sliceable | Dynamic collections, queues, sorting |
| Tuple | (1, 2, 3) | Immutable | Ordered, 0-indexed, unpackable | Fixed coordinates, record tuples, dict keys |
| Dictionary | { "key": "val" } | Mutable | Key-value pairs, O(1) hash lookups | Structured entities, lookup tables, JSON mapping |
| Set | { 1, 2, 3 } | Mutable | Unordered, unique values only | Deduplication, membership test, set operations (&, |, -) |
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}Gracefully recovering from runtime failures using try, except, else, and finally.
# 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.")Encapsulating state and behavior into reusable classes with __init__ and methods.
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__Safely streaming files with context managers and utilizing Python's built-in batteries.
# 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())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)})Write and modify real Python code. Test syntax, collections, OOP, and exceptions with immediate feedback!
Diagnose 6 authentic bugs encountered by developers learning Python.
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.
def calculate_average(scores):
total = sum(scores)
count = len(scores) # ⚠️ Mixed Tab character with 4 spaces!
return total / countTabError: inconsistent use of tabs and spaces in indentation
File "math_utils.py", line 3
count = len(scores)
^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?
for ... in, enumerate(), and Python 3.10+ match-case for expressive data handling.try/except blocks to handle edge cases cleanly.with open(...) as f: to prevent leaks.