Core Structures

Python Trainer

Functions · Lists · Tuples · Dicts · String Methods · File I/O · Error Handling

Functions — def, parameters, return
Functions let you wrap reusable logic with a name. Pass in inputs (parameters), do work, and return a result. You call the same function as many times as you need.
💡
def defines a function. return sends a value back to whoever called it. Parameters are local variables — they only exist inside the function.
Scenario — shipping cost calculator
An online store charges shipping based on weight. Write a function that takes weight and distance, applies the rate, and returns the total cost. Call it for several different orders.
$0.05
$2.50
Python code
shipping.py

          
Output — function called 4 times
live result
def keyword return value f":.2f money
🔁
Default parameters — you can set a default value: def ship(weight, dist, rate=0.05). Then calling ship(10, 100) uses the default rate automatically. Great for optional settings.
Lists — ordered, mutable collections
A list holds multiple values in order. You can add, remove, sort, and slice them. Lists use square brackets [ ] and are zero-indexed.
💡
Zero-indexed: the first item is index [0], not [1]. Negative indexes count from the end — [-1] is always the last item. Slicing [1:3] gives items at index 1 and 2 (end is exclusive).
Scenario — warehouse inventory
A warehouse tracks stock quantities for several products. Use a list to store them, then find the total, min, max, and sorted order.
5 items
Python code
inventory.py

          
Output
live result
[ ] list len() sum() sorted() min() max()
Index & slice explorer
0
Tuples — ordered, immutable collections
Tuples look like lists but use parentheses ( ) and cannot be changed after creation. Use them for fixed data: coordinates, RGB colors, database records — things that shouldn't be accidentally modified.
🔒
Immutable means once you create a tuple, you can't append, remove, or change items. This is a feature — it makes your data safe and lets Python optimize memory. You can still index and slice tuples exactly like lists.
Scenario — store locations
Each store location is stored as a tuple: (name, latitude, longitude, year_opened). You can unpack the tuple into variables, or access fields by index.
Store 1
Python code
locations.py

          
Output + tuple unpacking
live result
( ) tuple unpacking [index] access
📦
Functions can return tuples — this is how Python returns multiple values at once. return width, height is actually returning a tuple (width, height), and you unpack it with w, h = get_dimensions().
Dictionaries — key → value lookup
Dicts store data as key-value pairs using curly braces { }. Look up any value instantly by its key — no looping needed. Keys must be unique.
💡
dict["key"] raises an error if the key doesn't exist. dict.get("key", default) is safer — it returns the default instead of crashing. Use .keys(), .values(), .items() to loop over a dict.
Scenario — employee directory
Store employee records as a dict. Each employee ID maps to another dict with their name, department, and salary. Look up, update, and iterate over the data.
4 employees
5%
Python code
employees.py

          
Output
live result
{ } dict .get() safe .items() loop
String Methods
Strings have built-in methods for cleaning, searching, splitting, and transforming text. These are called with dot notation: my_string.method().
Interactive playground — type any text
Python code
strings.py

          
Output — every method, live
live result
.strip() .upper() .lower() .split() .join() .replace() .count() .find() .startswith()
File I/O — reading and writing files
Use open() to read and write files. The with statement automatically closes the file when you're done — always use it. Files are text by default.
💡
Mode matters: "r" = read (default), "w" = write (overwrites), "a" = append (adds to end), "r+" = read and write. Always use with open(...) — it handles closing even if an error happens.
Scenario — contact book saved to a file
Write a list of contacts to a .txt file, then read it back. Each contact has a name and phone number. Shows write mode, append mode, and read mode.
📄
Simulated file contents — what contacts.txt would look like on disk:
Python code — write, append, read
contacts.py

          
Output — reading the file back
live result
open() with "w" "a" "r" .write() .read() .splitlines()
Error Handling — try / except / finally
Errors (exceptions) crash your program unless you catch them. try runs code that might fail. except catches the error and handles it gracefully. finally always runs — perfect for cleanup.
🛡
Be specific with exceptions. Catching Exception is a safety net but you should try to catch the exact type — ValueError, ZeroDivisionError, FileNotFoundError, etc. This makes bugs easier to find.
Scenario — user input validator
A user types a value into a form. Your code must handle bad input (letters where a number is expected), division by zero, and missing files — all without crashing.
Simulate user input (try typing letters, 0, or a valid number):
or type your own:
Python code
validator.py

          
Output — what happens at runtime
live result
try / except ValueError ZeroDivisionError finally
📌
Common exception types to know:
ValueError — wrong type of value (e.g. int("abc"))
TypeError — wrong type (e.g. "5" + 5)
ZeroDivisionError — dividing by zero
FileNotFoundError — file doesn't exist
KeyError — dict key not found
IndexError — list index out of range