Core Concepts of Python
Python has 6 building blocks: Variables & Types, Control Flow (if/for/while), Functions, Data Structures (list/dict/set/tuple), Modules & Packages, and Object-Oriented Programming (classes).
The Big Picture
Every Python program is built from these six building blocks. Master them and you can build anything.
Explain Like I'm 12
Python is like LEGO. Variables are individual bricks (they hold values). Data structures are containers (boxes of bricks). Functions are instruction booklets (reusable steps). Control flow is the order you follow (if this, do that). Modules are separate LEGO sets you can combine. Classes are custom brick designs you create yourself.
Cheat Sheet
| Concept | Syntax | Plain English |
|---|---|---|
| Variables | x = 42 |
Give a name to a value |
| Control Flow | if x > 0: / for i in range(10): |
Make decisions and repeat things |
| Functions | def greet(name): |
Reusable blocks of code |
| Data Structures | [1,2,3] / {"key": "val"} |
Organized collections of data |
| Modules | import pandas as pd |
Use other people's code |
| Classes (OOP) | class Dog: |
Create your own data types |
The 6 Building Blocks
Variables & Types
Variables are names that point to values. Python has four basic types you'll use constantly: int (integers), float (decimals), str (text), and bool (True/False). Python is dynamically typed, so you never declare a type — Python figures it out at runtime.
name = "Alice" # str
age = 30 # int
pi = 3.14 # float
active = True # bool
print(f"{name} is {age}") # f-string
Since Python 3.5, you can add type hints — optional annotations that document what types a function expects. They don't enforce anything at runtime, but they make your code easier to read and help IDEs catch bugs.
def greet(name: str) -> str:. They make code self-documenting and help tools like mypy catch bugs before you run anything.
Control Flow
Control flow is how you tell Python to make decisions and repeat actions. The three workhorses: if/elif/else for branching, for loops for iterating, and while loops for repeating until a condition changes.
The crucial thing to understand: indentation IS syntax in Python. Other languages use curly braces {} to group code — Python uses 4 spaces. This isn't optional; it's how the interpreter knows which code belongs to which block.
for item in items:
if item.price > 100:
print(f"Expensive: {item.name}")
else:
print(f"Budget: {item.name}")
Python also has break (exit a loop early), continue (skip to the next iteration), and pass (do nothing — placeholder for empty blocks).
IndentationError and refuse to run.
Functions
Functions let you write a block of code once and reuse it everywhere. Define with def, pass in parameters, get back a result with return. Python supports default arguments, *args (variable positional args), and **kwargs (variable keyword args).
def calculate_tax(amount, rate=0.1):
"""Calculate tax for a given amount."""
return amount * rate
tax = calculate_tax(1000) # 100.0 (uses default rate)
tax = calculate_tax(1000, 0.2) # 200.0 (custom rate)
Functions are first-class objects in Python — you can assign them to variables, pass them as arguments, and return them from other functions. This makes patterns like decorators and callbacks natural.
def). It describes what the function does, and you can access it with help(calculate_tax) or calculate_tax.__doc__.
Data Structures
Python has four built-in data structures. Knowing when to use each one is just as important as knowing how.
names = ["Alice", "Bob", "Charlie"] # list
scores = {"Alice": 95, "Bob": 87} # dict
unique = {1, 2, 3, 2, 1} # set → {1, 2, 3}
point = (10, 20) # tuple (immutable)
evens = [x for x in range(10) if x % 2 == 0] # comprehension
| Structure | Ordered? | Mutable? | Duplicates? | Use Case |
|---|---|---|---|---|
| List | Yes | Yes | Yes | Sequences you'll modify (shopping list, results) |
| Dict | Yes (3.7+) | Yes | Keys: No | Key-value lookups (user profiles, configs) |
| Set | No | Yes | No | Unique items, membership tests, deduplication |
| Tuple | Yes | No | Yes | Fixed data (coordinates, function return values) |
Modules & Packages
A module is any .py file. A package is a folder of modules. Python's import system lets you use code from the standard library, third-party packages (installed via pip), or your own files.
import pandas as pd # import entire module with alias
from datetime import datetime # import specific class
from pathlib import Path # modern file path handling
Third-party packages live on PyPI (Python Package Index). Install with pip install pandas. Always use a virtual environment (python -m venv .venv) to keep project dependencies isolated.
python -m venv .venv, then activate it (source .venv/bin/activate on Mac/Linux, .venv\Scripts\activate on Windows). This prevents dependency conflicts between projects.
Classes (OOP)
Classes let you create your own data types that bundle data (attributes) and behavior (methods) together. The __init__ method runs when you create an instance. The self parameter refers to the current instance.
class Patient:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Patient: {self.name}, Age: {self.age}"
p = Patient("Alice", 30)
print(p.greet()) # Patient: Alice, Age: 30
Python supports inheritance (create specialized versions of a class), encapsulation (prefix attributes with _ to signal "private"), and polymorphism (different classes responding to the same method name). But Python's philosophy is practical: use classes when they make sense, not just because you can.
@dataclass (Python 3.7+), which auto-generates __init__, __repr__, and other boilerplate. For simple data containers, @dataclass saves you a lot of typing.
Python vs Other Languages
How does Python compare to the other languages you'll encounter?
| Feature | Python | JavaScript | Java | SQL |
|---|---|---|---|---|
| Typing | Dynamic | Dynamic | Static | Static (schemas) |
| Compiled? | Interpreted | JIT compiled | Compiled (bytecode) | Declarative |
| Primary Use | Data, AI, web, scripts | Web frontend + backend | Enterprise apps | Database queries |
| Learning Curve | Easy | Moderate | Steep | Easy (for basics) |
| Speed | Slower | Fast (V8 engine) | Fast | Depends on DB engine |
| Code Verbosity | Low (concise) | Moderate | High (verbose) | Low |
Test Yourself
What are Python's 4 basic data types?
None for "no value."What is the difference between a list and a tuple?
Why does Python use indentation instead of curly braces?
What does import pandas as pd do?
pd.DataFrame() instead of pandas.DataFrame(). The alias is a convention (almost everyone uses pd for pandas, np for numpy, plt for matplotlib). It saves typing and makes code consistent across the community.What is self in a Python class?
self refers to the current instance of the class. When you call p.greet(), Python automatically passes p as the self parameter. It's how methods access the instance's attributes (self.name, self.age). Unlike Java's this, you must explicitly include self as the first parameter of every instance method.