Getting Back to Python
This tutorial assumes you already learned Python once. You’re not starting from zero — you’re rebuilding fluency.
Variables and Data Types: How Python Stores Information
Python is dynamically typed: variables point to objects, not fixed types.
Core built-in data types
| Type | Purpose | Mutable |
|---|---|---|
int |
Whole numbers | ❌ |
float |
Decimal numbers | ❌ |
bool |
True / False | ❌ |
str |
Text | ❌ |
list |
Ordered collection | ✅ |
tuple |
Fixed ordered collection | ❌ |
dict |
Key–value mapping | ✅ |
set |
Unique unordered values | ✅ |
NoneType |
Represents “nothing” | ❌ |
Strings: Text Is a Sequence
Accessing characters
Common operations
When to use strings
- Any human-readable text
- File contents
- Identifiers, labels, names
Strings are immutable — every modification creates a new string.
Lists: Ordered, Changeable Collections
Accessing elements
Modifying lists
Looping
When to use lists
- Ordered data
- When duplicates matter
- When you need to add/remove items
Tuples: Fixed, Ordered Data
Accessing
Tuples cannot be changed:
When to use tuples
- Fixed-size data (coordinates, RGB values)
- When structure matters more than mutability
- As dictionary keys
Dictionaries: Key–Value Data
Accessing values
Modifying
Looping
When to use dictionaries
- Named data
- Structured records
- Fast lookups by key
Think of dicts as Python’s basic data structure for real-world objects.
Sets: Unique, Unordered Values
Result:
Operations
Set math
a = {1, 2, 3}
b = {3, 4}
a & b # intersection → {3}
a | b # union → {1, 2, 3, 4}
a - b # difference → {1, 2}
When to use sets
- Remove duplicates
- Membership tests
- Comparing collections
Conditions: Making Decisions
Truthiness
Falsy values:
0""[],{},set()NoneFalse
Loops: Repeating Work
for loops
while loops
Use for when possible; while when the end condition is unknown.
Functions: Reusable Behavior
Parameters and return values
Functions that modify data
When to write a function
- You repeat code
- You want clarity
- You want to test logic in isolation
Accessing Data Inside Data Structures
Nested structures
Access:
Defensive access
File Handling: Reading and Writing Data
Reading a text file
Line-by-line
Writing a file
Appending
The with statement:
- Automatically closes files
- Prevents resource leaks
- Is the correct default
Common Data File Types
JSON (structured data)
import json
with open("data.json") as f:
data = json.load(f)
with open("out.json", "w") as f:
json.dump(data, f, indent=2)
JSON maps naturally to:
- dict → object
- list → array
CSV (tabular data)
Choosing the Right Data Type
| Need | Use |
|---|---|
| Ordered data | list |
| Fixed structure | tuple |
| Named fields | dict |
| Uniqueness | set |
| Text | str |
| Absence | None |
Rule of thumb:
If you’re naming things → use a dict. If you’re counting things → use a list or set.
Python Functions — The Essentials
What is a function?
A function is a named block of code that:
- takes input
- does something
- returns output
Use it:
Parameters and return values
No return → returns None.
Default and keyword arguments
Functions and data structures
Functions usually take and return lists or dicts.
Good practice:
- Don’t modify inputs unless you mean to
- Return new data
Returning multiple values
Python returns a tuple.
Local variables and scope
Inside ≠ outside.
Avoid using global.
Functions calling functions
Small functions compose well.
Basic error handling inside functions
Classes
What is a class
A class groups data (attributes) and behavior (methods) together.
Think of a class as:
A blueprint for creating objects.
An object (instance) is created like this:
Why classes exist
Use classes when:
- Data and functions naturally belong together
- You’re passing around the same group of values
- You want to model a real “thing”
If functions are verbs, classes are nouns.
The __init__ method
__init__ runs when an object is created.
selfrefers to the current object- Attributes are attached to
self
Instance methods
Methods are functions that belong to a class.
Usage:
Attributes vs local variables
xexists only inside the methodself.yexists on the object
Passing data into a class
Methods that return values
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
Classes and data structures
Objects often wrap dictionaries or lists.
class Cart:
def __init__(self):
self.items = []
def add(self, name, price):
self.items.append({"name": name, "price": price})
def total(self):
return sum(item["price"] for item in self.items)
When NOT to use classes
Don’t use a class if:
- A function and dict are enough
- There’s no shared state
- You only need one operation
Many Python programs are mostly functions + dicts.
A common beginner mistake
❌ Doing too much in one class
✅ Prefer small, focused classes
__str__: Make objects readable
class User:
def __init__(self, name):
self.name = name
def __str__(self):
return f"User({self.name})"
Very light inheritance (optional)
Use inheritance only when there is a true “is-a” relationship.
If this feels unnecessary — skip it. Many Python codebases barely use inheritance.
Classes vs functions — quick rule
| Use case | Prefer |
|---|---|
| One operation | Function |
| Multiple operations on shared data | Class |
| Data with behavior | Class |
| Stateless logic | Function |