# Benjamin Patch
> AI, Ethics, and Practical Code
Benjamin Patch is the Founder & CEO of Skybloom and an AI practitioner based in Southern California. This site covers AI ethics, AI fundamentals, and practical programming guides aimed at developers working in or adjacent to the AI space.
## Posts
### Python Kickstart (part 4): Functions
URL: https://benjaminpatch.com/posts/2026/Apr/10/python-kickstart-p4-functions/
> Functions transform tangled scripts into clean, reusable building blocks. Learn how to define functions, pass arguments, return values, manage scope, and document your work. Packed with movie-themed examples that reinforce every concept. Let's get coding!
Welcome back to our Python Kickstart series! In [part 1](/posts/2025/May/13/when-vibe-coding-fails-python-kickstart-p1/), we installed Python and covered variables. In [part 2](/posts/2025/Jul/09/python-kickstart-p2-data-types-structures/), we explored data types and data structures. And in [part 3](/posts/2025/Jul/31/python-kickstart-p3-control-flow-conditionals/), we made our programs dynamic with control flow and conditionals. Now we're ready to tackle one of the most important concepts in programming: **functions**.
If control flow is the director's vision that shapes how a story unfolds, then functions are the reusable scenes, shots, and setups that a production team can assemble into a finished film. A skilled director doesn't reinvent how to block a dialogue scene every single time - they rely on proven techniques they can apply again and again. Functions give your Python programs that same kind of leverage.
#### Why Functions Matter
Before we dive into syntax, let's talk about _why_ functions exist in the first place. Imagine you're writing a program that analyzes several films. For each one, you need to compute its age, classify its runtime, and format a summary line. Without functions, you'd copy and paste that logic for every movie. When you inevitably find a bug, you'd have to fix it in every single copy.
Functions solve this by letting you:
- **Reuse code** - write logic once, call it as many times as you want
- **Name ideas** - a well-named function documents _what_ your code does
- **Isolate complexity** - hide fiddly details behind a clean interface
- **Test smaller pieces** - verify one chunk of logic at a time
- **Avoid repetition** - following the DRY principle (Don't Repeat Yourself)
As your programs grow, functions become the difference between code you can maintain and code you dread opening. Let's see how to create them.
#### Defining Your First Function
In Python, you define a function using the `def` keyword, followed by the function's name, a pair of parentheses, and a colon. The body of the function is indented underneath - just like the code blocks we saw with conditionals and loops in part 3.
```python
# A simple function that prints a movie introduction
def introduce_movie():
print("π¬ Now presenting a cinematic masterpiece...")
print("Please silence your phones and enjoy the show.")
# Calling the function
introduce_movie()
introduce_movie() # We can call it as many times as we want
```
Output:
```
π¬ Now presenting a cinematic masterpiece...
Please silence your phones and enjoy the show.
π¬ Now presenting a cinematic masterpiece...
Please silence your phones and enjoy the show.
```
A few things to notice:
1. **`def`** tells Python we're defining a function
2. **The function name** follows the same rules as variable names - lowercase with underscores, no spaces, can't start with a number
3. **The parentheses `()`** will hold parameters (we'll get there in a moment)
4. **The colon `:`** and indented block define the function's body
5. **Calling the function** means writing its name followed by `()` - this actually runs the code inside
Defining a function and calling a function are two separate steps. Python reads the `def` block and remembers it, but nothing happens until you actually call the function by name.
#### Parameters: Passing Data to Functions
Functions become far more useful when you can pass information into them. The values a function accepts are called **parameters** when you define the function, and **arguments** when you call it.
```python
# A function that takes a movie title as a parameter
def introduce_movie(title):
print(f"π¬ Now presenting: {title}")
print("Please silence your phones and enjoy the show.")
# Passing different arguments
introduce_movie("The Godfather")
introduce_movie("Seven Samurai")
introduce_movie("In the Mood for Love")
```
Output:
```
π¬ Now presenting: The Godfather
Please silence your phones and enjoy the show.
π¬ Now presenting: Seven Samurai
Please silence your phones and enjoy the show.
π¬ Now presenting: In the Mood for Love
Please silence your phones and enjoy the show.
```
Functions can take multiple parameters, separated by commas:
```python
# Multiple parameters for richer output
def introduce_movie(title, director, year):
print(f"π¬ Now presenting: {title} ({year})")
print(f" Directed by {director}")
print(" Please silence your phones and enjoy the show.\n")
introduce_movie("Vertigo", "Alfred Hitchcock", 1958)
introduce_movie("Parasite", "Bong Joon-ho", 2019)
```
When you call a function with multiple arguments, Python matches them to parameters **in order**. `"Vertigo"` goes into `title`, `"Alfred Hitchcock"` goes into `director`, and `1958` goes into `year`. Getting that order wrong is a common bug - we'll talk about how to avoid it shortly.
#### Return Values: Getting Data Back
Printing things is useful, but often you want a function to _compute_ a value and hand it back so other code can use it. That's where the `return` statement comes in.
```python
# Calculate how many years ago a film was released
def years_since_release(release_year, current_year):
return current_year - release_year
# The return value can be stored in a variable
godfather_age = years_since_release(1972, 2026)
casablanca_age = years_since_release(1942, 2026)
print(f"The Godfather is {godfather_age} years old")
print(f"Casablanca is {casablanca_age} years old")
# Or used directly in an expression
print(f"2001: A Space Odyssey is {years_since_release(1968, 2026)} years old")
```
Output:
```
The Godfather is 54 years old
Casablanca is 84 years old
2001: A Space Odyssey is 58 years old
```
A function that uses `return` immediately stops executing and hands back whatever value you specify. If you don't write a `return` statement at all, the function returns a special value called `None` - Python's way of saying "nothing here."
You can also return multiple values by separating them with commas, which Python packs into a tuple:
```python
# Return multiple pieces of related information
def analyze_runtime(minutes):
hours = minutes // 60
leftover_minutes = minutes % 60
is_epic = minutes >= 180
return hours, leftover_minutes, is_epic
# Unpack the returned tuple directly into variables
hrs, mins, epic = analyze_runtime(228) # Lawrence of Arabia
print(f"Lawrence of Arabia: {hrs}h {mins}m")
if epic:
print("This is an epic-length film!")
```
Output:
```
Lawrence of Arabia: 3h 48m
This is an epic-length film!
```
This kind of multi-return is perfect when several pieces of data naturally belong together, like the components of a runtime analysis.
#### Default Parameters
Sometimes a parameter has an obvious default value that most callers will want. You can provide one directly in the function definition:
```python
# The current_year has a sensible default
def years_since_release(release_year, current_year=2026):
return current_year - release_year
# Callers can omit current_year when the default is fine
print(years_since_release(1972)) # Uses default: 54
print(years_since_release(1972, 2030)) # Override: 58
```
Default parameters make functions more flexible without forcing every caller to supply every value. One important rule: parameters _with_ defaults must come _after_ parameters without defaults in the function signature. Python will raise a `SyntaxError` if you try it the other way around.
```python
# β
Correct β required parameters come first
def rate_movie(title, rating=5.0):
return f"{title}: {rating}/10"
# β Incorrect β will cause SyntaxError
# def rate_movie(title="Untitled", rating):
# return f"{title}: {rating}/10"
```
#### Keyword Arguments: Calling by Name
When a function takes several parameters, remembering their order can be tricky - especially if some of them are the same type. Python lets you pass arguments **by name**, which makes your code clearer and lets you skip over parameters with defaults.
```python
def describe_film(title, director, year, genre="Drama", runtime=120):
print(f"π½οΈ {title} ({year})")
print(f" Director: {director}")
print(f" Genre: {genre}")
print(f" Runtime: {runtime} minutes\n")
# Positional arguments β order matters
describe_film("Pulp Fiction", "Quentin Tarantino", 1994)
# Keyword arguments β order doesn't matter
describe_film(
title="Spirited Away",
year=2001,
director="Hayao Miyazaki",
genre="Animation",
runtime=125,
)
# Mix positional and keyword β positional must come first
describe_film("Seven Samurai", "Akira Kurosawa", 1954, runtime=207)
```
Notice how the `describe_film("Seven Samurai", ...)` call skips `genre` entirely (using the default `"Drama"`) while still providing a custom `runtime`. Keyword arguments are a powerful way to make function calls self-documenting.
#### Flexible Arguments with `*args` and `**kwargs`
Occasionally you'll want a function that can accept an arbitrary number of arguments. Python provides two special syntaxes for this: `*args` for extra positional arguments, and `**kwargs` for extra keyword arguments.
```python
# *args collects extra positional arguments into a tuple
def average_rating(*ratings):
if not ratings:
return 0.0
return sum(ratings) / len(ratings)
print(average_rating(9.2, 8.7, 9.0)) # Three ratings
print(average_rating(8.3)) # One rating
print(average_rating(9.2, 8.7, 9.0, 7.5, 8.1)) # Five ratings
# **kwargs collects extra keyword arguments into a dictionary
def build_movie_entry(title, **details):
entry = {"title": title}
entry.update(details)
return entry
inception = build_movie_entry(
"Inception",
director="Christopher Nolan",
year=2010,
genre="Sci-Fi Thriller",
rating=8.8,
)
print(inception)
```
Output:
```
8.966666666666667
8.3
8.5
{'title': 'Inception', 'director': 'Christopher Nolan', 'year': 2010, 'genre': 'Sci-Fi Thriller', 'rating': 8.8}
```
The names `args` and `kwargs` are just convention - what matters is the `*` and `**`. Use these features sparingly: they're powerful, but they also make a function's signature less obvious at a glance.
#### Variable Scope: Where Names Live
When you create a variable inside a function, it exists only within that function. This is called **local scope**. Variables defined outside any function live in **global scope** and are visible throughout the file.
```python
# Global variable
favorite_director = "Akira Kurosawa"
def film_recommendation():
# Local variable β only visible inside this function
recommended_film = "Ran"
print(f"{favorite_director} recommendation: {recommended_film}")
film_recommendation()
print(f"Favorite director: {favorite_director}")
# Uncommenting this line would raise NameError β recommended_film doesn't exist out here
# print(recommended_film)
```
Scope keeps your program organized. A function can freely use its own variables without accidentally clobbering something in the rest of the program. As a general rule, prefer _passing data in_ through parameters and _getting data out_ through return values, rather than reaching out to global variables. Functions that only work with their inputs and outputs are much easier to understand and reuse. Here are two alternative designs β pick one:
```python
# β Fragile β relies on a global variable
catalog = []
def add_to_catalog(title):
catalog.append(title)
# β
Clearer β the data dependency is explicit
def add_to_catalog(catalog, title):
catalog.append(title)
return catalog
```
Both patterns work, but the second version is easier to test and reason about because everything the function touches is right there in the signature.
#### Docstrings: Documenting Your Functions
Python has a built-in convention for documenting functions called a **docstring** - a triple-quoted string placed on the first line of a function's body. Tools like editors, `help()`, and documentation generators can read these strings automatically.
```python
def classify_runtime(minutes):
"""Return a human-readable category for a film's runtime.
Args:
minutes: The film's runtime in whole minutes.
Returns:
A string describing the runtime category.
"""
if minutes < 90:
return "Short Feature"
elif minutes < 150:
return "Standard Feature"
elif minutes < 180:
return "Long Feature"
else:
return "Epic"
print(classify_runtime(87)) # Short Feature
print(classify_runtime(175)) # Long Feature
print(classify_runtime(228)) # Epic
# You can also read the docstring at runtime
help(classify_runtime)
```
Good docstrings explain _what_ a function does, _what_ its parameters mean, and _what_ it returns. They're a gift to your future self - and to anyone else who inherits your code.
#### Lambda Functions: Tiny Anonymous Functions
Sometimes you need a very small function for a single purpose - often to pass to another function. Python lets you write these as **lambda functions**, which are unnamed and limited to a single expression.
```python
# A list of movies as (title, rating) tuples
movies = [
("Citizen Kane", 8.3),
("The Godfather", 9.2),
("Seven Samurai", 8.6),
("Vertigo", 8.3),
("Tokyo Story", 8.2),
]
# Sort by rating (highest first) using a lambda as the sort key
sorted_movies = sorted(movies, key=lambda movie: movie[1], reverse=True)
for title, rating in sorted_movies:
print(f"{rating} β {title}")
```
The lambda here, `lambda movie: movie[1]`, is shorthand for a function that takes one argument called `movie` and returns its second element (the rating). We could have written a regular `def` function instead, but for a one-line helper passed directly to `sorted()`, a lambda keeps the code compact.
Use lambdas for small, obvious expressions. If the logic gets complex, reach for a regular `def` - the name alone will make the code easier to read.
#### Common Mistakes and How to Avoid Them
Functions unlock a lot of power, but they also introduce some new ways to trip yourself up. Watch out for these.
##### Forgetting to Call the Function
```python
def greet_director(name):
return f"Welcome, {name}!"
# β This just references the function object β no greeting happens
print(greet_director)
# β
The parentheses actually call the function
print(greet_director("Sofia Coppola"))
```
##### Forgetting to Return a Value
```python
# β This function prints the result but doesn't return it
def double_rating(rating):
print(rating * 2)
result = double_rating(4.5) # prints 9.0 as a side effect
print(result) # None β because we forgot to `return`
# β
Return the value so callers can use it
def double_rating(rating):
return rating * 2
result = double_rating(4.5)
print(result) # 9.0
```
##### Mutable Default Arguments
This one surprises almost everyone the first time they hit it. Default arguments are evaluated _once_, when the function is defined - not each time it's called. If the default is a mutable object like a list, every call shares the same list.
```python
# β Dangerous β the default list is shared across calls
def add_to_watchlist(title, watchlist=[]):
watchlist.append(title)
return watchlist
print(add_to_watchlist("Rear Window")) # ['Rear Window']
print(add_to_watchlist("Rashomon")) # ['Rear Window', 'Rashomon'] β oops!
# β
Use None as the default and create a fresh list inside
def add_to_watchlist(title, watchlist=None):
if watchlist is None:
watchlist = []
watchlist.append(title)
return watchlist
print(add_to_watchlist("Rear Window")) # ['Rear Window']
print(add_to_watchlist("Rashomon")) # ['Rashomon']
```
Remember this rule: **never use a mutable default argument**. Use `None` as the sentinel and create the real default inside the function.
#### Bringing It All Together
Let's combine everything from this article into a small film analysis tool. We'll use multiple functions that work together - each with a single, clear job.
```python
def classify_runtime(minutes):
"""Return a human-readable runtime category."""
if minutes < 90:
return "Short Feature"
elif minutes < 150:
return "Standard Feature"
elif minutes < 180:
return "Long Feature"
else:
return "Epic"
def years_since_release(release_year, current_year=2026):
"""Return how many years have passed since a film's release."""
return current_year - release_year
def rating_verdict(rating):
"""Convert a numeric rating into a short critical verdict."""
if rating >= 9.0:
return "Masterpiece"
elif rating >= 8.0:
return "Highly Recommended"
elif rating >= 7.0:
return "Worth Watching"
else:
return "Mixed Reception"
def summarize_film(title, director, year, runtime, rating):
"""Print a full analysis line for a single film."""
age = years_since_release(year)
category = classify_runtime(runtime)
verdict = rating_verdict(rating)
print(f"π¬ {title} ({year}) β directed by {director}")
print(f" {category}, {runtime} min | {age} years old")
print(f" Rating: {rating}/10 β {verdict}\n")
def summarize_collection(films):
"""Summarize every film in a collection and report the average rating."""
for film in films:
summarize_film(**film)
average = sum(f["rating"] for f in films) / len(films)
print(f"π Average rating across {len(films)} films: {average:.2f}")
# Our curated collection
collection = [
{
"title": "Seven Samurai",
"director": "Akira Kurosawa",
"year": 1954,
"runtime": 207,
"rating": 8.6,
},
{
"title": "The Godfather",
"director": "Francis Ford Coppola",
"year": 1972,
"runtime": 175,
"rating": 9.2,
},
{
"title": "In the Mood for Love",
"director": "Wong Kar-wai",
"year": 2000,
"runtime": 98,
"rating": 8.1,
},
]
summarize_collection(collection)
```
Notice how each function does _one thing_ and is easy to understand on its own. `summarize_film` doesn't need to know how runtimes are classified - it just calls `classify_runtime`. `summarize_collection` doesn't need to know how individual films are formatted - it just calls `summarize_film`. This kind of layered design is exactly what functions are for, and it's how real-world Python programs are built.
Also notice the `**film` syntax in `summarize_film(**film)`. That's the mirror image of `**kwargs`: it unpacks a dictionary into keyword arguments. Because the keys in each dictionary match the parameter names of `summarize_film`, Python can pass them through automatically.
#### What's Next?
Functions are the turning point where Python stops feeling like a sequence of commands and starts feeling like a real programming language. With conditionals, loops, and functions in your toolkit, you can build surprisingly sophisticated programs.
In the next installment, **Python Kickstart Part 5: Classes and Object-Oriented Programming**, we'll take the next step: bundling data _and_ the functions that operate on it into reusable types of our own. If functions are reusable scenes, classes are reusable characters - complete with their own state and behavior.
#### Practice Suggestions
Before moving on, try building these small projects to reinforce your understanding of functions:
- **Film Rating Calculator**: Write a function that takes a list of ratings and returns the average, highest, and lowest as a tuple. Bonus points for handling empty lists gracefully.
- **Watchlist Manager**: Create functions for adding, removing, and listing films in a watchlist. Make sure you avoid the mutable default argument trap!
- **Runtime Formatter**: Write a function that converts a runtime in minutes into a string like `"3h 27m"`. Try giving it a default format and a keyword argument for a different style (e.g. `"207 minutes"`).
- **Director Filter**: Given a list of film dictionaries, write a function that returns all films by a given director. Use keyword arguments to support optional filters like minimum rating.
Resist the urge to jam everything into one giant function. A good rule of thumb: if you can't describe what a function does in a single sentence, it's probably trying to do too much. Break it up.
As always, the best way to internalize these concepts is to write code, break it, and fix it. Every function you write makes the next one easier.
Happy coding, and I'll see you in Part 5!
---
### Python Kickstart (part 3): Control Flow and Conditionals
URL: https://benjaminpatch.com/posts/2025/Jul/31/python-kickstart-p3-control-flow-conditionals/
> Transform static code into intelligent programs with Python's control flow statements. Learn if/elif/else conditionals, for and while loops, and how to combine them for complex logic. Complete with practical examples using movie data and film analysis scenarios to reinforce key programming concepts. Let's dive in!
Welcome back to our Python Kickstart series! In [part 1](/posts/2025/May/13/when-vibe-coding-fails-python-kickstart-p1/), we covered Python installation, variables, and basic concepts. In [part 2](/posts/2025/Jul/09/python-kickstart-p2-data-types-structures/), we explored data types and data structures. Now we're ready to make our programs truly dynamic with control flow and conditionals.
Control flow is what transforms static code into intelligent programs that can make decisions and repeat actions based on conditions. Think of it as the director's vision that determines how a film's story unfolds - sometimes linear, sometimes nonlinear with flashbacks and/or parallel narratives, but always purposeful. Just as a great director uses different techniques to guide the audience through a narrative, Python's control flow statements guide your program through different logical paths.
#### Understanding Program Flow
Before diving into specific statements, it's important to understand that Python programs execute line by line, from top to bottom. Control flow statements allow you to change this natural order by:
- **Making decisions** with conditional statements (`if`, `elif`, `else`)
- **Repeating actions** with loops (`for`, `while`)
- **Jumping out of or skipping parts** of loops (`break`, `continue`)
Let's explore each of these powerful tools.
#### Conditional Statements: Teaching Programs to Decide
Conditional statements are the foundation of program logic. They allow your code to examine conditions and execute different blocks of code based on whether those conditions are true or false.
##### The `if` Statement
The simplest conditional statement is `if`. It executes code only when a condition is true:
```python
# Movie recommendation system
imdb_rating = 9.2
movie_title = "The Godfather"
if imdb_rating > 9.0:
print(f"{movie_title} is a certified masterpiece!")
print("This film belongs in every cinephile's collection.")
print("Highly recommended for serious film study.")
```
Notice several important things about this code:
1. **The colon (`:`)** at the end of the `if` line - this is required syntax
2. **Indentation** - everything indented under the `if` statement only executes when the condition is true
3. **The condition** - `imdb_rating > 9.0` evaluates to either `True` or `False`
Python uses indentation (typically 4 spaces) to group code blocks together. This is different from many other programming languages that use curly braces `{}`. The indented code forms a "block" that executes as a unit.
##### The `if`-`else` Statement
Often you want to execute one piece of code when a condition is true, and different code when it's false. This is where `else` comes in:
```python
# Film festival submission guidelines
runtime_minutes = 195
festival_max_runtime = 180
if runtime_minutes <= festival_max_runtime:
print("β This film meets the festival's runtime requirements.")
print("Status: Approved for submission.")
submission_fee = 75
else:
print("β This film exceeds the festival's maximum runtime.")
print("Status: Requires editing or alternate festival selection.")
submission_fee = 0
print(f"Submission fee: ${submission_fee}")
```
The `else` clause provides an alternative path when the `if` condition is false. Exactly one of the two code blocks will execute - never both, never neither.
##### The `if`-`elif`-`else` Chain
For multiple conditions, use `elif` (short for "else if"). This allows you to test several conditions in sequence:
```python
# Movie era classification system
release_year = 1962
director = "David Lean"
if release_year < 1930:
era = "Silent Era"
characteristics = "Visual storytelling, title cards, live musical accompaniment"
elif release_year < 1960:
era = "Golden Age of Hollywood"
characteristics = "Studio system, star power, Technicolor innovation"
elif release_year < 1980:
era = "New Hollywood"
characteristics = "Auteur theory, social commentary, experimental techniques"
elif release_year < 2000:
era = "Modern Era"
characteristics = "Digital effects, blockbuster mentality, franchise development"
else:
era = "Contemporary Cinema"
characteristics = "Streaming platforms, international perspectives, diverse voices"
print(f"'{director}' directed films during the {era}")
print(f"Key characteristics: {characteristics}")
# Additional context based on specific era
if era == "New Hollywood":
print("This was a revolutionary period that challenged traditional filmmaking.")
```
Python evaluates `elif` conditions in order and executes the first block where the condition is true. Once a condition matches, the remaining `elif` and `else` blocks are skipped.
##### Comparison Operators: The Building Blocks of Conditions
Python provides several operators for making comparisons. Understanding these is crucial for writing effective conditional statements:
```python
# Comprehensive movie analysis using comparison operators
citizen_kane_year = 1941
vertigo_year = 1958
lawrence_rating = 8.3
kane_rating = 8.3
casablanca_votes = 558_278
kane_votes = 442_988
print("=== MOVIE COMPARISON ANALYSIS ===")
# Equality and inequality
print(f"Same IMDB rating? {lawrence_rating == kane_rating}")
print(f"Different release years? {citizen_kane_year != vertigo_year}")
# Numerical comparisons
print(f"Vertigo released after Citizen Kane? {vertigo_year > citizen_kane_year}")
print(f"Kane released before 1950? {citizen_kane_year < 1950}")
print(f"Lawrence rating at least 8.0? {lawrence_rating >= 8.0}")
print(f"Kane rating 8.3 or lower? {kane_rating <= 8.3}")
# Practical application
age_difference = vertigo_year - citizen_kane_year
if age_difference > 15:
print(f"These films span different cinematic generations ({age_difference} years apart)")
```
##### Logical Operators: Combining Conditions
Real-world decisions often depend on multiple factors. Python's logical operators `and`, `or`, and `not` let you combine conditions:
```python
# Advanced movie filtering for awards consideration
movie_title = "Lawrence of Arabia"
runtime = 228
imdb_rating = 8.3
won_best_picture = True
director = "David Lean"
box_office_millions = 70.0
print(f"Analyzing: {movie_title}")
# Using 'and' - ALL conditions must be true
if runtime > 180 and imdb_rating > 8.0 and won_best_picture:
print("β Qualifies as an Epic Masterpiece")
print(" - Extended runtime showcases ambitious scope")
print(" - High critical acclaim confirms artistic merit")
print(" - Academy recognition validates cultural impact")
# Using 'or' - AT LEAST ONE condition must be true
if director == "David Lean" or director == "Akira Kurosawa" or director == "John Ford":
print("β Directed by a Master of Epic Cinema")
# Using 'not' - condition must be FALSE
if not (box_office_millions > 100):
print("β Not a major commercial success")
print(" Note: Artistic merit often differs from box office performance")
# Complex logical combinations
is_prestigious = (won_best_picture and imdb_rating > 8.0) or (director in ["Kubrick", "Hitchcock", "Welles"])
if is_prestigious:
print("β Considered a prestigious film by multiple criteria")
```
##### String Comparisons and the `in` Operator
Python can compare strings and check for membership using the `in` operator:
```python
# Genre analysis and director style identification
movie_title = "North by Northwest"
genre_tags = ["thriller", "suspense", "espionage", "romance"]
director_style = "Alfred Hitchcock"
# String comparison (case-sensitive)
if director_style == "Alfred Hitchcock":
print("Master of Suspense film detected!")
# Membership testing with 'in'
if "thriller" in genre_tags:
print("This film will keep you on the edge of your seat")
if "romance" in genre_tags and "suspense" in genre_tags:
print("Perfect blend of heart and tension")
# Substring checking in strings
film_title_lower = movie_title.lower()
if "north" in film_title_lower:
print("Geographic reference in title suggests a journey narrative")
# Checking multiple possibilities
hitchcock_classics = ["Psycho", "Vertigo", "North by Northwest", "Rear Window", "The Birds"]
if movie_title in hitchcock_classics:
print(f"'{movie_title}' is among Hitchcock's most celebrated works")
```
#### Loops: Repeating Actions Efficiently
Loops allow you to execute code multiple times without writing repetitive statements. They're essential for processing collections of data and performing repetitive tasks.
##### The `for` Loop: Iterating Over Collections
Use `for` loops when you want to process each item in a collection:
```python
# Displaying a curated film festival lineup
festival_films = [
"8Β½",
"Persona",
"The Rules of the Game",
"Tokyo Story",
"The 400 Blows"
]
print("CANNES RETROSPECTIVE: International Cinema Masterpieces")
print("=" * 55)
for film in festival_films:
print(f"π¬ {film}")
# Add specific context for certain films
if film == "8Β½":
print(" Federico Fellini's surreal meditation on creativity")
elif film == "Tokyo Story":
print(" YasujirΕ Ozu's profound family drama")
print(f"\nTotal films in retrospective: {len(festival_films)}")
```
You can iterate over strings character by character:
```python
# Analyzing film title composition
title = "CASABLANCA"
vowel_count = 0
consonant_count = 0
print(f"Analyzing the title: {title}")
print("Character breakdown:")
for character in title:
if character in "AEIOU":
print(f" '{character}' - vowel")
vowel_count += 1
elif character.isalpha():
print(f" '{character}' - consonant")
consonant_count += 1
print(f"\nSummary: {vowel_count} vowels, {consonant_count} consonants")
print(f"The title has a {vowel_count/len(title):.1%} vowel ratio")
```
##### Using `range()` for Controlled Iteration
The `range()` function generates sequences of numbers, perfect for controlled loops:
```python
# Film festival countdown and ranking system
print("π VENICE FILM FESTIVAL COUNTDOWN")
print("Premiere begins in...")
for seconds in range(5, 0, -1): # Start at 5, stop before 0, step by -1
print(f" {seconds}...")
print("π¬ Action! Festival begins!")
# Ranking films with position numbers
critically_acclaimed = [
("Citizen Kane", 8.3),
("The Godfather", 9.2),
("8Β½", 8.0),
("Vertigo", 8.3)
]
print("\nπ CRITICS' CHOICE RANKINGS:")
for i in range(len(critically_acclaimed)):
title, rating = critically_acclaimed[i]
rank = i + 1
# Add special notation for top positions
if rank == 1:
medal = "π₯"
elif rank == 2:
medal = "π₯"
elif rank == 3:
medal = "π₯"
else:
medal = f"{rank}."
print(f"{medal} {title} (IMDB: {rating})")
```
##### The `while` Loop: Conditional Repetition
Use `while` loops when you want to repeat code as long as a condition remains true:
```python
# Box office tracking simulation
film_title = "Lawrence of Arabia"
opening_weekend = 4.2 # millions (1962 dollars)
total_gross = 0.0
week = 1
target_gross = 15.0 # Break-even point
print(f"π BOX OFFICE TRACKING: {film_title}")
print("=" * 45)
while total_gross < target_gross:
# Simulate weekly box office decline
weekly_earnings = opening_weekend * (0.85 ** (week - 1))
total_gross += weekly_earnings
print(f"Week {week:2}: ${weekly_earnings:4.1f}M (Total: ${total_gross:5.1f}M)")
# Weekly performance analysis
if week == 1:
print(" Strong opening weekend performance")
elif weekly_earnings < 1.0:
print(" Box office momentum slowing")
week += 1
# Safety break to prevent infinite loops
if week > 20:
print(" Extended theatrical run completed")
break
print(f"\nπ― Final gross: ${total_gross:.1f}M after {week-1} weeks")
if total_gross >= target_gross:
print("β
Film achieved commercial success!")
else:
print("π Film built audience through word-of-mouth")
```
##### Loop Control: `break` and `continue`
Fine-tune loop execution with `break` and `continue` statements:
```python
# Film database search with early termination
directors_and_films = [
("Christopher Nolan", "Dunkirk"),
("Martin Scorsese", "Goodfellas"),
("Stanley Kubrick", "2001: A Space Odyssey"),
("Akira Kurosawa", "Seven Samurai"),
("Christopher Nolan", "Inception"),
("Wong Kar-wai", "In the Mood for Love")
]
target_director = "Stanley Kubrick"
search_count = 0
print(f"π Searching for films by {target_director}:")
for director, film in directors_and_films:
search_count += 1
# Skip films by other directors
if director != target_director:
print(f" Skipping: {film} by {director}")
continue
# Found a match!
print(f"β
Found: '{film}' by {director}")
print(f" Search completed after checking {search_count} entries")
break # Exit loop after finding first match
else:
# This 'else' clause runs only if the loop completes without 'break'
print(f"β No films by {target_director} found in database")
print("π Search operation finished")
```
#### Nested Control Structures
You can combine conditional statements and loops to create sophisticated program logic:
```python
# Film festival programming system
festival_submissions = [
{"title": "Amour", "country": "Austria", "runtime": 127, "genre": "Drama"},
{"title": "Holy Motors", "country": "France", "runtime": 115, "genre": "Fantasy"},
{"title": "The Master", "country": "USA", "runtime": 137, "genre": "Drama"},
{"title": "Beyond the Hills", "country": "Romania", "runtime": 150, "genre": "Drama"}
]
print("πͺ FESTIVAL PROGRAMMING COMMITTEE REVIEW")
print("=" * 50)
accepted_films = []
rejected_films = []
for submission in festival_submissions:
title = submission["title"]
runtime = submission["runtime"]
genre = submission["genre"]
country = submission["country"]
print(f"\nπ½οΈ Reviewing: {title} ({country})")
# Multiple criteria evaluation
if runtime > 180:
print(" β Rejected: Exceeds maximum runtime")
rejected_films.append(title)
continue
if genre == "Drama" and runtime > 120:
print(" β οΈ Long drama - requires special consideration")
if country in ["France", "Italy", "Germany"]:
print(" β
Accepted: European arthouse cinema")
accepted_films.append(title)
else:
print(" π Under review: Non-European long drama")
elif runtime <= 120:
print(" β
Accepted: Appropriate runtime")
accepted_films.append(title)
else:
print(" π Under review: Standard evaluation needed")
print(f"\nπ PROGRAMMING RESULTS:")
print(f" Accepted: {len(accepted_films)} films")
print(f" Rejected: {len(rejected_films)} films")
if accepted_films:
print(" π¬ Accepted films:")
for film in accepted_films:
print(f" β’ {film}")
```
#### Common Mistakes and How to Avoid Them
Understanding common pitfalls will help you write more reliable code:
##### Indentation Errors
```python
# β Incorrect - will cause IndentationError
rating = 8.5
if rating > 8.0:
print("Excellent film!") # Not indented!
# β
Correct indentation
if rating > 8.0:
print("Excellent film!")
print("Highly recommended!")
```
##### Assignment vs. Comparison
```python
# β Common mistake - using assignment (=) instead of comparison (==)
director = "Kubrick"
if director = "Kubrick": # SyntaxError!
print("Master filmmaker")
# β
Correct comparison
if director == "Kubrick":
print("Master filmmaker")
```
##### Infinite Loops
```python
# β Dangerous - infinite loop
counter = 1
while counter <= 5:
print(f"Week {counter}")
# Forgot to increment counter!
# β
Safe loop with proper increment
counter = 1
while counter <= 5:
print(f"Week {counter}")
counter += 1 # Essential!
```
#### What's Next?
You now have the tools to create programs that make intelligent decisions and efficiently process data through repetition. Control flow and conditionals are fundamental to virtually every meaningful program you'll write.
In our next installment, [**Python Kickstart Part 4: Functions**](/posts/2026/Apr/10/python-kickstart-p4-functions/), we'll explore how to organize your code into reusable blocks, making your programs more modular, maintainable, and powerful. Functions will allow you to avoid repetition and create more sophisticated applications by breaking complex problems into manageable pieces.
#### Practice Suggestions
Before moving on, try building these projects to reinforce your understanding:
- **Movie Recommendation Engine**: Create a program that suggests films based on user preferences for genre, decade, and rating thresholds
- **Film Festival Scheduler**: Build a system that organizes screenings based on runtime, venue capacity, and genre diversity
- **Box Office Tracker**: Simulate and analyze the financial performance of films over multiple weeks
Remember, the key to mastering these concepts is hands-on practice. Start with simple examples and gradually build more complex logic. Each conditional statement and loop you write strengthens your programming intuition.
The more comfortable you become with control flow, the more naturally you'll think in terms of program logic - and the better equipped you'll be to understand, debug, and improve any Python code you encounter.
Happy coding, and I'll see you in Part 4!
---
### Python Kickstart (part 2): Data Types and Data Structures
URL: https://benjaminpatch.com/posts/2025/Jul/09/python-kickstart-p2-data-types-structures/
> Let's dive deeper into Python's fundamental building blocks: data types and data structures. Understanding these concepts is crucial for writing effective Python programs. Think of data types as the different kinds of information your program can work with, while data structures are the containers that organize and store that information. Let's get started!
Welcome back to our Python Kickstart series! In [part 1](/posts/2025/May/13/when-vibe-coding-fails-python-kickstart-p1/), we covered the basics of Python installation, variables, the `print()` function, and got our feet wet with running Python code. Now it's time to dive deeper into Python's fundamental building blocks: data types and data structures.
Understanding these concepts is crucial for writing effective Python programs. Think of data types as the different kinds of information your program can work with, while data structures are the containers that organize and store that information. Just like a film director needs to understand different shot types and how to arrange them into scenes, a Python programmer needs to master these foundational elements.
#### Three Basic Data Types
Python has three basic data types that you'll use constantly: strings, numbers, and booleans. Let's explore each one with fun examples from movies!
##### Strings
Strings are sequences of characters enclosed in quotes. They're perfect for storing text data like movie titles, actor names, or dialogue. You can use either single quotes (`'`) or double quotes (`"`), but be consistent within your project.
```python
# Movie titles and names
movie_title = "The Shawshank Redemption"
director = "Frank Darabont"
lead_actor = 'Tim Robbins'
print(movie_title)
print(f"Directed by: {director}")
print(f"Starring: {lead_actor}")
```
Notice the `f` before the string in the last two print statements? This creates an **f-string** (formatted string literal), which lets you embed variables directly inside strings using curly braces `{}`. This is much cleaner than concatenating strings with `+`.
You can also create multi-line strings using triple quotes:
```python
movie_review = """
The Godfather is a masterpiece of American cinema.
Francis Ford Coppola's direction combined with
Marlon Brando's iconic performance creates
an unforgettable experience.
"""
print(movie_review)
```
##### Numbers
Python handles two main types of numbers: integers (whole numbers) and floats (decimal numbers). Both are incredibly useful for storing numerical data.
```python
# Integers
release_year = 1972
runtime_minutes = 175
box_office_millions = 286
# Floats
imdb_rating = 9.2
rotten_tomatoes_score = 97.5
print(f"The Godfather ({release_year})")
print(f"Runtime: {runtime_minutes} minutes")
print(f"Box office: ${box_office_millions} million")
print(f"IMDB Rating: {imdb_rating}/10")
print(f"Rotten Tomatoes: {rotten_tomatoes_score}%")
```
You can perform mathematical operations on numbers:
```python
# Calculate decades since release
current_year = 2025
decades_since_release = (current_year - release_year) / 10
print(f"The Godfather was released {decades_since_release} decades ago")
```
##### Booleans
Booleans represent truth values: either `True` or `False`. They're essential for decision-making in your programs and are often the result of comparisons.
```python
# Boolean values
is_classic = True
won_oscar = True
is_sequel = False
# Comparison operations that return booleans
is_highly_rated = imdb_rating > 9.0
is_long_movie = runtime_minutes > 180
is_recent = release_year > 2000
print(f"Is it a classic? {is_classic}")
print(f"Highly rated? {is_highly_rated}")
print(f"Long movie? {is_long_movie}")
print(f"Recent film? {is_recent}")
```
#### Common Data Type Mistakes
Let's look at some errors beginners often encounter with data types:
```python
# Mixing strings and numbers without conversion
year = "1968"
current_year = 2025
# This will cause a TypeError
# age_of_movie = current_year - year # Error!
# Instead, convert the string to an integer
age_of_movie = current_year - int(year)
print(f"2001: A Space Odyssey is {age_of_movie} years old")
```
Another common mistake is forgetting quotes around strings:
```python
# This will cause a NameError
# director = Stanley Kubrick # Error!
# Correct way:
director = "Stanley Kubrick"
print(director)
```
#### Python Data Structures
Now that we understand basic data types, let's explore Python's built-in data structures. These are containers that hold multiple pieces of data and are incredibly powerful for organizing information.
##### Lists
Lists are ordered collections of items that can be changed (mutable). They're perfect for storing sequences of related data like movie collections or cast members.
```python
# Creating lists
kubrick_films = ["2001: A Space Odyssey", "The Shining", "A Clockwork Orange", "Dr. Strangelove"]
box_office_numbers = [190.7, 47.0, 26.6, 9.5]
directors = ["Stanley Kubrick", "Orson Welles", "Christopher Nolan", "Greta Gerwig"]
# Accessing list items (indexing starts at 0)
print(f"First Kubrick film in our list: {kubrick_films[0]}")
print(f"Last director: {directors[-1]}") # Negative indexing starts from the end
# Adding items to lists
kubrick_films.append("Full Metal Jacket")
directors.insert(0, "Martin Scorsese") # Insert at specific position
print(f"Updated Kubrick films: {kubrick_films}")
print(f"Updated directors: {directors}")
```
Lists support many useful methods:
```python
# More list operations
nolan_films = ["Inception", "Interstellar", "The Dark Knight", "Dunkirk"]
print(f"Number of films: {len(nolan_films)}")
print(f"Is 'Inception' in the list? {'Inception' in nolan_films}")
# Sorting
nolan_films.sort()
print(f"Alphabetically sorted: {nolan_films}")
```
##### Tuples
Tuples are like lists, but they're immutable (cannot be changed after creation). They're perfect for storing related data that should stay together, like movie information.
```python
# Creating tuples
citizen_kane = ("Citizen Kane", 1941, "Orson Welles", 119)
casablanca = ("Casablanca", 1942, "Michael Curtiz", 102)
# Unpacking tuples
title, year, director, runtime = citizen_kane
print(f"{title} ({year}) directed by {director}, runtime: {runtime} minutes")
# Tuples are immutable - this would cause an error:
# citizen_kane[0] = "Kane" # Error!
```
Tuples are often used for coordinates, database records, or any grouped data that shouldn't change:
```python
# Movie ratings (title, imdb_rating, rotten_tomatoes)
movie_ratings = [
("The Godfather", 9.2, 97),
("Schindler's List", 9.0, 98),
("Pulp Fiction", 8.9, 92)
]
for title, imdb, rt in movie_ratings:
print(f"{title}: IMDB {imdb}, RT {rt}%")
```
##### Sets
Sets are unordered collections of unique items. They're excellent for removing duplicates and performing set operations like finding common elements.
```python
# Creating sets
scorsese_actors = {"Robert De Niro", "Leonardo DiCaprio", "Joe Pesci", "Robert De Niro"}
tarantino_actors = {"Samuel L. Jackson", "Uma Thurman", "Leonardo DiCaprio", "John Travolta"}
print(f"Scorsese actors: {scorsese_actors}") # Notice duplicate removed
print(f"Tarantino actors: {tarantino_actors}")
# Set operations
common_actors = scorsese_actors & tarantino_actors # Intersection
all_actors = scorsese_actors | tarantino_actors # Union
scorsese_only = scorsese_actors - tarantino_actors # Difference
print(f"Actors who worked with both: {common_actors}")
print(f"All actors: {all_actors}")
print(f"Only in Scorsese films: {scorsese_only}")
```
Sets are also useful for checking membership quickly:
```python
oscar_winners = {"Meryl Streep", "Tom Hanks", "Frances McDormand", "Daniel Day-Lewis"}
actors_to_check = ["Tom Hanks", "Ryan Gosling", "Meryl Streep"]
for actor in actors_to_check:
if actor in oscar_winners:
print(f"{actor} is an Oscar winner!")
else:
print(f"{actor} hasn't won an Oscar yet.")
```
##### Dictionaries
Dictionaries store key-value pairs and are incredibly useful for structured data. Think of them as lookup tables where each key maps to a value.
```python
# Creating dictionaries
the_godfather = {
"title": "The Godfather",
"year": 1972,
"director": "Francis Ford Coppola",
"runtime": 175,
"genre": "Crime Drama",
"imdb_rating": 9.2
}
# Accessing dictionary values
print(f"Movie: {the_godfather['title']}")
print(f"Director: {the_godfather['director']}")
print(f"Year: {the_godfather['year']}")
# Adding new key-value pairs
the_godfather["box_office"] = 286000000
the_godfather["lead_actor"] = "Marlon Brando"
print(f"Box office: ${the_godfather['box_office']:,}")
```
Dictionaries are perfect for more complex data structures:
```python
# Movie database
movie_database = {
"kubrick": {
"name": "Stanley Kubrick",
"notable_films": ["2001: A Space Odyssey", "The Shining", "A Clockwork Orange"],
"birth_year": 1928,
"nationality": "American"
},
"welles": {
"name": "Orson Welles",
"notable_films": ["Citizen Kane", "The Third Man", "Touch of Evil"],
"birth_year": 1915,
"nationality": "American"
}
}
# Accessing nested data
print(f"Stanley Kubrick's films: {movie_database['kubrick']['notable_films']}")
print(f"Orson Welles was born in {movie_database['welles']['birth_year']}")
# Iterating through dictionaries
for director_key, director_info in movie_database.items():
print(f"\n{director_info['name']} ({director_info['nationality']})")
for film in director_info['notable_films']:
print(f" - {film}")
```
#### Common Data Structure Mistakes
Here are some errors to watch out for:
**List Index Errors:**
```python
actors = ["Tom Hanks", "Meryl Streep", "Robert De Niro"]
# This will cause an IndexError
# print(actors[5]) # Error! List only has 3 items (indices 0, 1, 2)
# Safe way to access:
if len(actors) > 5:
print(actors[5])
else:
print("Not enough actors in the list")
```
**Dictionary Key Errors:**
```python
movie = {"title": "Inception", "year": 2010}
# This will cause a KeyError
# print(movie["director"]) # Error! Key doesn't exist
# Safe ways to access:
print(movie.get("director", "Director unknown"))
# or
if "director" in movie:
print(movie["director"])
```
#### When to Use Each Data Structure
Here's a practical guide for choosing the right data structure:
- **Lists**: When you need an ordered, changeable collection (movie watchlist, cast in order of appearance)
- **Tuples**: When you need an ordered, unchangeable collection (movie details, coordinates)
- **Sets**: When you need unique items or set operations (genres, avoiding duplicate actors)
- **Dictionaries**: When you need key-value relationships (movie details, actor information)
#### Bringing It All Together
Let's create a practical example that combines multiple data types and structures:
```python
# Movie recommendation system
movie_collection = {
"drama": [
{"title": "The Shawshank Redemption", "year": 1994, "rating": 9.3},
{"title": "Schindler's List", "year": 1993, "rating": 9.0},
{"title": "12 Angry Men", "year": 1957, "rating": 9.0}
],
"sci_fi": [
{"title": "2001: A Space Odyssey", "year": 1968, "rating": 8.3},
{"title": "Blade Runner", "year": 1982, "rating": 8.1},
{"title": "Interstellar", "year": 2014, "rating": 8.6}
]
}
# Function to recommend movies by genre
def recommend_movies(genre, min_rating=8.0):
if genre not in movie_collection:
return f"Sorry, no {genre} movies in our collection."
recommendations = []
for movie in movie_collection[genre]:
if movie["rating"] >= min_rating:
recommendations.append(f"{movie['title']} ({movie['year']}) - {movie['rating']}")
return recommendations
# Get recommendations
drama_recs = recommend_movies("drama", 9.0)
sci_fi_recs = recommend_movies("sci_fi", 8.5)
print("Highly-rated Drama recommendations:")
for rec in drama_recs:
print(f" - {rec}")
print("\nGreat Sci-Fi recommendations:")
for rec in sci_fi_recs:
print(f" - {rec}")
```
#### What's Next?
You now have a solid foundation in Python's basic data types and data structures! These are the building blocks you'll use in virtually every Python program you write. Whether you're building a web application, analyzing data, or creating the next great piece of software, these concepts will serve you well.
In the next part of our Python Kickstart series, we'll [explore Python's control flow and conditionals](/posts/2025/Jul/31/python-kickstart-p3-control-flow-conditionals/) to create dynamic programs that make intelligent decisions and execute repetitive tasks efficiently.
#### Practice Improves Your Programming
Remember, the best way to master these concepts is through practice. Try creating your own examples using your favorite movies, TV shows, or books. Build a small program that organizes your media collection, or create a simple movie rating system. The more you experiment with these data types and structures, the more natural they'll become.
Keep coding, keep learning, and remember: understanding these fundamentals will make you a much more effective programmer, whether you're working with an AI assistant or writing code from scratch. As we learned in part 1, vibe coding might be fun, but solid fundamental knowledge is what pays the bills!
Thanks for following along with Python Kickstart part 2. Until then next time, happy coding!
---
### When Vibe Coding Fails: Python Kickstart (part 1)
URL: https://benjaminpatch.com/posts/2025/May/13/when-vibe-coding-fails-python-kickstart-p1/
> Welcome to part one of my Python Kickstart series! Let's discuss why you should still learn Python in the age of vibe coding. Then we'll get our feet wet by learning about running Python code. An introduction to variables, the print function, basic errors, and code comments. Let's get started!
#### Why Learn Python?
From web development to data science to machine learning applications, Python has become one of today's most in-demand programming languages. Being skilled with it opens countless possibilities for your career. Its clean syntax and logical structure make it easy to learn and even fun to use!
Python's massive number of powerful modules, packages, and frameworks extend the language into virtually any domain of interest. Not to mention this is all fully open-source, making it free to use, modify, and redistribute - including for commercial purposes.
#### Why Isn't Vibe Coding the Answer?
Now, you may have heard some AI startup CEOs proclaim it is essentially a "waste of time to learn how to code in 2025."[1](#works-cited) I strongly disagree with these comments for several reasons. To start, I have first-hand experience asking LLMs (Large Language Models) to write and/or edit various types of code on my behalf. And while their speed and general capabilities can be astonishing, like people, they still make mistakes. And these mistakes can lead to broken and/or highly unmaintainable codebases.
To catch and correct mistakes from LLM-generated code (AKA vibe coding), you need to understand the fundamentals of the programming languages, modules, packages, and frameworks your application requires. Otherwise, it's like asking an LLM a general question in English and receiving a response in Japanese. If you have no understanding of Japanese, you will be hard-pressed to refine any output it produces.
Plus, let's not forget those AI startup CEOs have a vested interest in you being totally reliant on their products. Knowledge is power. Please don't outsource your critical thinking skills to AI. It's a tool, not a replacement for your brain.
#### Is There a Place for AI in Coding?
Even with that being said, there absolutely is a place for AI-assisted coding. Once you understand the basics, AI tools can supercharge your productivity - even acting as a paired-programming partner. The key is understanding what these LLMs excel at, and when you need to take the lead.
The first step in getting to that point is understanding the fundamentals of Python - or any programming language for that matter. As I recently read, "Vibe coding is fun, but **vibe refactoring** pays the bills."[2](#works-cited)
With that in mind, let's kickstart our knowledge of Python programming!
#### Install Python 3
If you don't already have a Python development environment set up, there are several ways you can do this. The method I recommend is creating a virtual environment using `pyenv`. If you're not familiar with installing Python via `pyenv`, please reference [Simple Python Virtual Environments: Linux and Mac](/posts/2025/Jan/30/simple-python-virtual-environments-linux-mac/) where I explain the benefits of this approach and walk you through the necessary steps to get rolling.
As noted in the linked article above, Windows users should use [pyenv-win](https://github.com/pyenv-win/pyenv-win) instead.
Because this **Python Kickstart** series of articles is an introduction to the basic principles and syntax of the language, any currently supported version of Python 3 is sufficient to install. Support for all versions of Python 2 were sunset in January 2020[3](#works-cited), and it is quite different. So please use Python 3.
I generally recommend choosing the most current stable release (`3.13` as of this writing) unless your project specifically requires something older.
With Python 3 installed and running on your system, let's get started with this incredible programming language!
#### Run Python Code in Your Terminal
There are many ways to execute (or run) Python code, but for the purposes of learning the basics, I recommend using a combination of your system's terminal and a code editor. Let's start with your terminal, then we'll bring a code editor into the mix.
To run Python code in your terminal, simply type:
```bash
# Linux and Mac:
python3 # or just 'python' if pyenv was used to install Python
# or on Windows:
py
```
Press `enter` and the Python interpreter will open. It will look something like this (colors will vary based on your shell configuration):
```python
Python [version number] (plus info about your system)
Type "help", "copyright", "credits" or "license" for more information.
>>> # Python code goes here
```
From here, you can run any Python code. To exit the interpreter, type `ctrl-d` on Linux/Mac or `ctrl-z` on Windows, followed by `enter`. If that doesn't work, you can also exit by typing: `quit()` or `exit`, followed by `enter`.
#### Variables
```python
greeting = "Hello, Python!"
```
In the example above, `greeting` is the variable, and it is set to the `string` (a sequence of characters inside quotes) `Hello, Python!` The equals sign (`=`) is called an **assignment operator**. A few rules to keep in mind:
- Variables cannot start with a number. So `x1` is a valid variable, but `1x` is not valid and will throw a syntax error.
- Variables also cannot contain spaces or special characters other than an underscore (`_`).
- Traditionally, variables start with lowercase letters so they are not confused with a `class`. More on classes later in this series.
In Python, variables can be assigned to just about anything the language supports - as we will see moving forward.
#### Python's `print()` Function
If we open the Python interpreter in our terminal (`python3` on Linux/Mac or `py` on Windows), and enter the following two lines of code:
```python
greeting = "Hello, Python!"
print(greeting)
```
The output will be:
```
Hello, Python!
```
The `print()` function is built into Python and displays the specified message on screen. Anything inside the `()` becomes the output. We'll be using the `print()` function extensively so you gain a better understanding of what the code is doing.
#### Jump into a Code Editor
Writing and running code in the Python interpreter is fine for simple checks, but anything longer than a few lines should be written to a `.py` (Python) file with your preferred code editor.
If you don't yet have a preferred code editor, I recommend starting with [Visual Studio Code](https://code.visualstudio.com/). It's free, has excellent Python support (with a few free extensions), and runs well on Linux, Mac, and Windows.
If you would like to follow along with the following code examples, feel free to create a `.py` file in your code editor. As long as it ends with `.py`, it can be called almost anything you would like, I'll go with `python_kickstart.py`. Like variables, spaces and special characters (other than underscores) are not allowed. Your filename also cannot start with a number.
Now in our `.py` file, write the following code:
```python
x = 4 + 3
print(x)
```
Save your `python_kickstart.py` file.
Next, go back to your terminal and, if it is still running, exit the Python interpreter (`ctrl-d` on Linux/Mac or `ctrl-z` on Windows).
Then `cd` (change directory) into the location where `python_kickstart.py` lives. And run:
```bash
# Linux and Mac:
python3 python_kickstart.py
# or on Windows:
py python_kickstart.py
```
And your terminal will return:
```
7
```
Great job! You just asked Python to run the code in `python_kickstart.py` and return the results. In this case, Python didn't simply print `4 + 3` but it did the arithmetic and only printed the result.
Going forward, I encourage you to manually write out (refrain from copy and paste) and execute the code examples for the topics we'll be covering. Then create a few more samples following the same patterns but with different content. I find this to be the most effective way to retain, understand, and eventually apply these foundational Python programming concepts.
#### Python Errors
We all make mistakes. And when mistakes happen within your code, Python might throw an error message. This is nothing to be afraid of because Python error messages routinely provide helpful information - guiding you to narrow down the problem. For example, Python will point to the location where an error occurred with one or more `^` characters like this:
```python
python_error = "Let's see if this works."
print(python_error
```
output:
```python
File ".../python_kickstart.py", line 2
print(python_error
^
SyntaxError: '(' was never closed
```
This is called a `SyntaxError`, which means there is something wrong with the way our program is written β punctuation that does not belong, a command where it is not expected, or a missing parenthesis (as seen above) can all trigger a `SyntaxError`.
Between the specific line number being noted, the `^` pointing, and the `SyntaxError` message, this all makes it very clear what we did wrong. Thanks, Python!
Another common error type is called a `NameError`:
```python
print(best_movie)
```
With no further context, this Python code will output:
```python
Traceback (most recent call last):
File ".../python_kickstart.py", line 1, in
print(best_movie)
^^^^^^^^^^
NameError: name 'best_movie' is not defined
```
A `NameError` occurs when the Python interpreter sees a word it does not recognize. Code that contains something that looks like a variable but was never defined (as seen above) will throw such an error.
Again, this detailed feedback makes simple debugging much easier than the code simply failing and maybe outputting some cryptic message. Good programmers read and try to decipher error messages. Python tries to help where it can - going well beyond many other programming languages in this regard.
#### Python Comments
You may have already noticed the use of `#`. In Python, `#` indicates anything that follows on the same line, is a comment. Python ignores all comments when running code, so they do not affect the output.
Comments can be thought of as notes for people. In fact, many programmers use comments as a form of documentation. Stating the intended purpose of a function, for example, can help other developers (or your future self) follow the logic of the program.
```python
# This is a single-line comment
"""
This is a multi-line comment
Anything inside the triple quotes is also ignored by the Python interpreter
"""
```
A set of three single quotes also works:
```python
'''
Multi-line comments can also be surrounded by a set of three single quotes
The end result is the same as using a set of three double quotes
'''
```
Comments are a great way of explaining existing code or to outline future plans. Code comments are incredibly helpful and I encourage you to use them.
In fact, if you ever need to ask an AI model to generate code for you (in the future, only after you learn the basics), direct it to document the output with code comments. This way, even when the code is broken, you'll have a better idea what the AI was trying to do. Then you can use your Python skills to refactor and fix it!
#### Basic Python Data Types
In Python, there are three basic data types:
- Strings
- Numbers
- Booleans
The next article in this series dives into these data types and then continues with data structures, which are both crucial in writing effective Python programs. Thanks for your interest in learning Python, and I'll catch you next time!
Up next: [Python Kickstart (part 2): Data Types and Data Structures](/posts/2025/Jul/09/python-kickstart-p2-data-types-structures/)
#### Works Cited
1. [Replit CEO Explains Why Learning To Code Is Pointless In AI Era](https://www.ndtv.com/feature/replit-ceo-explains-why-learning-to-code-is-pointless-in-ai-era-instead-learn-how-to-8039962) - NDTV, accessed May 12, 2025.
2. [Vibe Coding Is Fun - But Vibe Refactoring Pays the Bills](https://dawidmakowski.com/en/2025/04/vibe-coding-is-fun-but-vibe-refactoring-pays-the-bills/) - Dawid Makowski, accessed May 12, 2025.
3. [Sunsetting Python 2](https://www.python.org/doc/sunset-python-2/) - python.org, accessed May 12, 2025.
---
### DeepSeek-R1: The Promise and Peril of Open-Source Model Distillation
URL: https://benjaminpatch.com/posts/2025/Feb/14/deepseek-r1-promise-and-peril-open-source-model-distillation/
> DeepSeek-R1 is a powerful AI reasoning model that has taken the world by surprise with its impressive capabilities. Let's examine some of the significant challenges and misconceptions facing the widespread adoption of DeepSeek-R1. Then we'll delve into the more promising aspects of open-source AI - striving for a balanced approach to assess the current state of this powerful technology.
DeepSeek-R1 is a powerful reasoning model developed by the Chinese AI research lab, DeepSeek. It has taken the world by surprise with its impressive capabilities which are comparable to those of OpenAI's ChatGPT-4, Anthropic's Claude, and Google's Gemini. This is particularly impressive because DeepSeek is believed to have been developed without the most advanced AI chips available to its American competitors1.
Unlike most other commercial AI research labs, DeepSeek has open-sourced its models, which makes the source code freely available for anyone to use, modify, and share - including for commercial purposes. The open-source nature of this project begs the question: Can DeepSeek be used as a teaching model to train other student models? If so, what are the implications of this readily available and cost-effective technology?
Let's start by examining some of the significant challenges and misconceptions facing the widespread adoption of DeepSeek-R1. Then we'll delve into the more promising aspects of open-source AI - striving for a balanced approach to assess the current state of this powerful technology.
#### Weak Safety Guardrails
Reporting has emerged from credible sources such as Cisco Systems and the University of Pennsylvania2 contending DeepSeek-R1 exhibits weak safety guardrails as compared to leading closed-source LLMs (Large Language Models), raising serious concerns about its security and potential for misuse.
If you are considering deploying DeepSeek-R1 or a distilled model derived from it (as discussed later in this article), please be aware2:
- DeepSeek-R1 exhibited a 100% attack success rate when tested against harmful prompts from the [HarmBench](https://www.harmbench.org/) dataset.
- It failed to block a single harmful prompt across categories including cybercrime, misinformation, illegal activities, and general harm.
- This performance contrasts sharply with other leading models that demonstrated at least partial resistance to such attacks.
- DeepSeek-R1's claimed cost-efficient training methods, including reinforcement learning and chain-of-thought self-evaluation, may have compromised its safety mechanisms.
#### Industry Response to Weak Guardrails
In light of these security concerns, major cloud providers are implementing additional safeguards:
- Amazon Web Services (AWS) is offering [Amazon Bedrock Guardrails](https://aws.amazon.com/blogs/machine-learning/deepseek-r1-model-now-available-in-amazon-bedrock-marketplace-and-amazon-sagemaker-jumpstart/) to provide configurable safeguards for DeepSeek-R1 deployments.
- Microsoft is implementing security measures for DeepSeek-R1 on [Azure AI Foundry](https://www.microsoft.com/en-us/security/blog/2025/02/13/securing-deepseek-and-other-ai-systems-with-microsoft-security/), including rigorous red teaming, safety evaluations, and built-in content filtering.
These findings highlight the critical importance of robust guardrails and security measures in LLM development and deployment, especially as these models become more powerful and widely used.
#### DeepSeek Training Cost Controversy
DeepSeek initially claimed that training R1 cost a mere $6 million. To put this in context, the leading AI models from American competitors cost hundreds of millions and sometimes even billions of dollars to train.
Understandably, DeepSeek's initial claim of around $6 million, while attention-grabbing, has been met with skepticism from industry analysts9. The $6 million likely represents only a portion of the total cost, specifically the GPU time for pre-training. It fails to account for many other essential expenses such as:
- Research and Development
- Data Acquisition and Preparation
- Personnel Costs
- Infrastructure Costs
A more realistic estimate of DeepSeek's total investment in AI development is around $1.6 billion. This figure encompasses the cost of hardware, software, data, personnel, and research. While significantly higher than the initial claim, this figure is still lower than the investments made by some American competitors9, 10.
#### Efficient Open-Source Engineering
While DeepSeek's initial claim of ultra-low-cost training was likely exaggerated for marketing purposes, it is evident that the AI firm has legitimately made significant strides in optimizing both architecture and training methods to reduce costs. These innovations have the potential to disrupt the AI industry, putting pressure on American companies to find new ways to improve efficiency and reduce the expenses associated with training large language models.
DeepSeek-R1's efficiency and performance stems from several important engineering decisions:
- It utilizes a **decoder-only transformer architecture** with multi-head latent attention3.
- DeepSeek-R1 combines **chain-of-thought reasoning** with **reinforcement learning**, where an autonomous agent learns to perform a task through trial and error without human instruction1.
- R1 uses a **mixture of experts (MoE) architecture**, which is less resource-intensive to train. The MoE architecture divides an AI model into separate entities or subnetworks, each specializing in a subset of the input data4. Then the model only activates the specific experts needed for a given task, making it more efficient1.
#### AI Model Distillation: A Primer
Instead of training a smaller model from scratch, **model distillation** offers a far more efficient approach by transferring knowledge from a larger, more complex model (the "teacher") to a smaller model (the "student"). The goal is to achieve comparable performance with the smaller model while reducing computational costs and latency5. If done correctly, this knowledge transfer does not lead to a loss of validity in the student model6.
The process involves generating a dataset where the teacher model provides outputs for a wide range of inputs. This dataset captures the teacher's behavior and decision-making patterns. The student model is then fine-tuned using this dataset, learning to mimic the teacher's responses. Techniques like **temperature scaling** are often employed to soften the output probabilities of the teacher, making it easier for the student to learn nuanced patterns5.
There are different types of model distillation, each with its own approach to knowledge transfer:
- **Response-Based Distillation:** The student model focuses on mimicking the teacher's predictions4.
- **Feature-Based Distillation:** The student model learns the internal features or representations learned by the teacher4.
- **Relation-Based Distillation:** The student model learns to understand the relationships between inputs and outputs4.
The choice of distillation process depends on the specific task and the desired outcome. Additionally, there are different training methods in model distillation, including offline distillation, where the student model learns from a static dataset generated by the teacher, and online distillation, where the student learns interactively from the teacher during training7.
#### DeepSeek as a Teaching Model
Given its open-source nature and impressive capabilities, DeepSeek is a strong contender to serve as a teaching model. Its comprehensive architecture and ability to perform complex reasoning tasks make it ideal for transferring knowledge to smaller, more specialized models.
Researchers and developers can leverage DeepSeek's open-source code and pre-trained weights to create datasets for distilling knowledge into student models. This can be achieved through various techniques, including **response-based distillation**, where the student model learns to mimic DeepSeek's outputs, or **feature-based distillation**, where the student model learns the internal representations of DeepSeek.
The availability of DeepSeek's architecture and training details allow for a deeper understanding of its inner workings, enabling developers to fine-tune student models more effectively. This can lead to the development of specialized models that excel in specific domains while maintaining efficiency and accuracy8.
Furthermore, using DeepSeek as a teaching model aligns with the broader movement towards transparency and wider participation in AI development9. By making its models open and accessible, DeepSeek encourages a collaborative approach to AI innovation, allowing developers and researchers to learn from and build upon its advancements.
#### Business Implications of Less Expensive Model Building
The open-sourcing of DeepSeek and the subsequent potential for less expensive model building have significant business implications:
- **Reduced Development Costs:** Distilling knowledge from DeepSeek can significantly reduce the cost of developing new AI models. This is particularly beneficial for startups and smaller companies that may not have the resources to train large models from scratch.
- **Faster Time-to-Market:** With reduced development costs and time, businesses can bring AI-powered products and services to market faster, gaining a competitive edge.
- **Increased Accessibility:** Less expensive model building makes AI technology more accessible to a wider range of businesses and organizations, democratizing access to advanced AI capabilities11.
- **Enhanced Customization:** Open-source models like DeepSeek allow for greater customization, enabling businesses to tailor AI solutions to their specific needs and industry requirements. This is a key advantage over closed models, which often offer limited flexibility8.
- **Innovation and Growth:** The availability of cost-effective AI models can foster innovation and drive the development of new applications across various industries11.
However, there are also potential challenges:
- **Competition:** The proliferation of AI models could lead to increased competition, potentially impacting the profitability of existing AI providers.
- **Security Risks:** Open-source models could be vulnerable to exploitation by malicious actors, requiring robust security measures to mitigate potential risks12.
- **Ethical Concerns:** The widespread use of AI models raises ethical concerns, such as bias and fairness, that need to be addressed through responsible development and deployment practices15.
#### Exponential Proliferation of Specialty Models
With the availability of DeepSeek and other open-source models, we will likely see an exponential proliferation of new specialty models. The reduced cost and increased accessibility of model-building technology will empower developers to create AI solutions tailored to specific domains and use cases.
This proliferation will likely lead to a surge in AI applications across various industries, including healthcare, finance, manufacturing, and more. We can expect to see specialized models for tasks such as medical diagnosis, fraud detection, customer service, and personalized education.
The open-source nature of these models will also foster collaboration and knowledge sharing, accelerating the pace of innovation in the AI field. This collaborative environment will drive the development of more sophisticated and effective AI solutions, addressing a wider range of challenges and opportunities.
This proliferation of models is not just about quantity; it's about a fundamental shift in how we approach technological discovery. Openness in this process is key to surviving threats and ensuring that power dispersion is necessary for technological progress16. This democratization of AI development has the potential to unlock new levels of innovation and problem-solving, leading to solutions that benefit a wider range of individuals and communities.
#### Conclusion
The release of DeepSeek-R1 as an open-source model marks a significant milestone in the evolution of artificial intelligence. Its potential to serve as a teaching model for distillation, coupled with the reduced cost of model building, will undoubtedly lead to an exponential proliferation of new specialty models. This will have profound implications for businesses, industries, and society as a whole, driving innovation, growth, and the democratization of AI technology.
This shift towards open-source AI has the potential to reshape the AI landscape, fostering greater collaboration, transparency, and accessibility. It could lead to a more diverse and inclusive AI ecosystem, where innovation is driven by a global community of developers and researchers. However, it is crucial to address the potential challenges and ethical concerns associated with this proliferation to ensure responsible and beneficial AI development and deployment.
Thank you for reading and I would love to hear your thoughts about DeepSeek and open-source AI on Bluesky: [@benjaminpatch.com](https://bsky.app/profile/benjaminpatch.com). Until next time, take care!
##### Works Cited
1. What is DeepSeek? AI Model Basics Explained - YouTube, accessed February 13, 2025, [https://www.youtube.com/watch?v=KTonvXhsxpc](https://www.youtube.com/watch?v=KTonvXhsxpc)
2. Evaluating Security Risks in DeepSeek and Other Frontier Reasoning Models - Cisco Systems, accessed February 13, 2025, [https://blogs.cisco.com/security/evaluating-security-risk-in-deepseek-and-other-frontier-reasoning-models](https://blogs.cisco.com/security/evaluating-security-risk-in-deepseek-and-other-frontier-reasoning-models)
3. DeepSeek - Wikipedia, accessed February 13, 2025, [https://en.wikipedia.org/wiki/DeepSeek](https://en.wikipedia.org/wiki/DeepSeek)
4. A pragmatic introduction to model distillation for AI developers - Labelbox, accessed February 13, 2025, [https://labelbox.com/blog/a-pragmatic-introduction-to-model-distillation-for-ai-developers/](https://labelbox.com/blog/a-pragmatic-introduction-to-model-distillation-for-ai-developers/)
5. Model Distillation - Humanloop, accessed February 13, 2025, [https://humanloop.com/blog/model-distillation](https://humanloop.com/blog/model-distillation)
6. Knowledge distillation - Wikipedia, accessed February 13, 2025, [https://en.wikipedia.org/wiki/Knowledge_distillation](https://en.wikipedia.org/wiki/Knowledge_distillation)
7. What is Model Distillation? - Labelbox, accessed February 13, 2025, [https://labelbox.com/guides/model-distillation/](https://labelbox.com/guides/model-distillation/)
8. How Open-Source Generative AI Models Affect Applications In Vertical Markets - Forbes, accessed February 13, 2025, [https://www.forbes.com/councils/forbestechcouncil/2024/10/08/how-open-source-generative-ai-models-affect-applications-in-vertical-markets/](https://www.forbes.com/councils/forbestechcouncil/2024/10/08/how-open-source-generative-ai-models-affect-applications-in-vertical-markets/)
9. DeepSeek's $6 Million AI Claim Debunked: True Costs Revealed - PC Outlet, accessed February 13, 2025, [https://pcoutlet.com/software/ai/deepseeks-6-million-ai-claim-exposed-as-myth-true-costs-revealed](https://pcoutlet.com/software/ai/deepseeks-6-million-ai-claim-exposed-as-myth-true-costs-revealed)
10. DeepSeek might not be as disruptive as claimed, firm reportedly has 50,000 Nvidia GPUs and spent $1.6 billion on buildouts - Tom's Hardware, accessed February 13, 2025, [https://www.tomshardware.com/tech-industry/artificial-intelligence/deepseek-might-not-be-as-disruptive-as-claimed-firm-reportedly-has-50-000-nvidia-gpus-and-spent-usd1-6-billion-on-buildouts](https://www.tomshardware.com/tech-industry/artificial-intelligence/deepseek-might-not-be-as-disruptive-as-claimed-firm-reportedly-has-50-000-nvidia-gpus-and-spent-usd1-6-billion-on-buildouts)
11. Open Source AI Models: Coding Outside the Proprietary Box - Neil Sahota, accessed February 13, 2025, [https://www.neilsahota.com/open-source-ai-models-coding-outside-the-proprietary-box/](https://www.neilsahota.com/open-source-ai-models-coding-outside-the-proprietary-box/)
12. Open-Source AI β Challenges, Opportunities & Ecosystem | by Abel Samot - Medium, accessed February 13, 2025, [https://medium.com/red-river-west/open-source-ai-mapping-advantages-debate-dd6be433eff6](https://medium.com/red-river-west/open-source-ai-mapping-advantages-debate-dd6be433eff6)
13. Risks and Opportunities of Open-Source Generative AI - arXiv, accessed February 13, 2025, [https://arxiv.org/html/2405.08597v1](https://arxiv.org/html/2405.08597v1)
14. With Open Source Artificial Intelligence, Don't Forget the Lessons of Open Source Software, accessed February 13, 2025, [https://www.cisa.gov/news-events/news/open-source-artificial-intelligence-dont-forget-lessons-open-source-software](https://www.cisa.gov/news-events/news/open-source-artificial-intelligence-dont-forget-lessons-open-source-software)
15. Why open-source is crucial for responsible AI development - The World Economic Forum, accessed February 13, 2025, [https://www.weforum.org/stories/2023/12/ai-regulation-open-source/](https://www.weforum.org/stories/2023/12/ai-regulation-open-source/)
16. Surviving a technological future: Technological proliferation and modes of discovery - PMC, accessed February 13, 2025, [https://pmc.ncbi.nlm.nih.gov/articles/PMC7094529/](https://pmc.ncbi.nlm.nih.gov/articles/PMC7094529/)
---
### Simple Python Virtual Environments: Linux and Mac
URL: https://benjaminpatch.com/posts/2025/Jan/30/simple-python-virtual-environments-linux-mac/
> Python is the most widely used programming language for projects involving artificial intelligence and machine learning. But regardless of what you use Python for, virtual environments are critical to essentially all development workflows. In this guide, you will learn why virtual environments are important and how to create and manage them.
Python is the most widely used programming language for projects involving artificial intelligence and machine learning. But regardless of what you use Python for, virtual environments are critical to essentially all development workflows. In this guide, you will learn why virtual environments are important and how to create and manage them.
Specifically, we will cover the installation, configuration, and basic use of `pyenv` to manage numerous versions of Python on your system. We will also explain how to use `venv` to create, activate, deactivate, and remove virtual Python environments. Finally, we will cover the management of external dependencies with `pip`.
The combination of these three tools will help us create simple, clean, and flexible virtual environments for a wide range of Python projects. Let's walk through the process together.
#### Why Virtual Environments?
It is best practice to create virtual environments to isolate project dependencies from the global Python installation and other projects. Imagine a situation where you are working on one project that is targeting the most recent version of Python and external packages. But you also inherited another project from other developers who wrote the code years ago for a much older version of Python and external packages.
By isolating the development environments for each of these projects, you can prevent conflicts between them and ensure each project runs with the specific version of Python and external packages it requires. Plus, you can quickly swap out versions of Python and dependencies to see if it leads to any problems.
Perhaps that old project only needs a few minor tweaks to run in modern environments. Maybe it will become more performant and secure with the upgrade. Virtual development environments can help you find out.
#### A Note for My Windows Friends
This guide is written for setting up virtual environments on Linux and macOS because that is where I spend most of my time. While some of these tools will work on Windows, it is not recommended. As noted in the documentation for the first tool we will be discussing, `pyenv`:
> `pyenv` does not officially support Windows and does not work in Windows outside the Windows Subsystem for Linux. Moreover, even there, the Pythons it installs are not native Windows versions but rather Linux versions running in a virtual machine -- so you won't get Windows-specific functionality.
>
> If you're in Windows, we recommend using @kirankotari's [pyenv-win](https://github.com/pyenv-win/pyenv-win) fork -- which does install native Windows Python versions.
After `pyenv-win` is installed and running Python on your Windows machine, you should be able to join us later in this guide in the [Use venv to Create Virtual Environments](#use-venv-to-create-virtual-environments) section since everything after that is done within Python itself.
Just keep in mind the syntax differences between running Python commands on Windows as compared to Linux and macOS. For example:
```bash
python3 --version # run Python commands on Linux and macOS
py --version # run the same Python command on Windows
```
#### Install `pyenv`
`pyenv` is the gold standard for managing multiple Python versions on your system. It allows you to easily install and switch between different Python interpreters globally or on a per-project level. It is simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well. Let's start by getting `pyenv` installed.
##### Linux
On your Linux distro of choice, run the following terminal command:
```bash
curl -fsSL https://pyenv.run | bash
```
##### macOS
On macOS, the Linux command above should work but using the Homebrew package manager is recommended by the developers of `pyenv`.
If you don't already have Homebrew running on your Mac, then please follow the installation instructions from [Homebrew's documentation](https://brew.sh/).
With Homebrew installed on your Mac, run the following terminal commands to update Homebrew itself and install `pyenv`:
```bash
brew update
brew install pyenv
```
##### Windows
As noted above, this guide is written for Linux and macOS. Windows users are encouraged to use [pyenv-win](https://github.com/pyenv-win/pyenv-win) instead. Detailed installation and usage instructions can be found in that project's documentation.
---
#### Shell Configurations
With `pyenv` installed, it now needs to be configured for your terminal's shell. This guide covers the three most common shells: Bash, Zsh, and Fish. If you are not sure which shell your system is using, run:
```bash
echo $0
```
And it will tell you. Then follow the steps outlined in the appropriate section below.
To learn more about shells, please see this informative article from TheLinuxCode: [Linux Shells for Beginners β Bash, Zsh, and Fish Explained and Compared](https://thelinuxcode.com/linux-shells-for-beginners-bash-zsh-and-fish-explained-and-compared/).
##### Bash
Bash (Bourne Again SHell) ships as the default shell on most Linux distros and older Macs.
If you are not using Bash, please skip this section.
Stock Bash startup files vary widely between Linux distributions. So, the most reliable way to get `pyenv` working in all environments is to append configuration commands to both `.bashrc` (for interactive shells) and the profile file that Bash would use (for login shells).
First, add the following commands to `~/.bashrc` by running the following in your terminal:
```bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init - bash)"' >> ~/.bashrc
```
Then, if you have `~/.profile`, `~/.bash_profile` or `~/.bash_login`, add the commands there as well. If you have none of these, create a `~/.profile` and add the commands there.
Run for `~/.profile`:
```bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.profile
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.profile
echo 'eval "$(pyenv init - bash)"' >> ~/.profile
```
Run for `~/.bash_profile`:
```bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(pyenv init - bash)"' >> ~/.bash_profile
```
##### Zsh
Zsh (Z SHell) ships as the default shell on newer Macs and a few Linux distros. But if desired, virtually any Linux distro can be configured to run Zsh.
If you are not using Zsh, please skip this section.
For Zsh shells, run:
```bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init - zsh)"' >> ~/.zshrc
```
##### Fish
As far as I know, Fish (Friendly Interactive Shell) does not ship as the default shell on any major Linux distros or macOS. It must be installed manually.
If you are not using Fish, please skip this section.
If you have Fish 3.2.0 or newer, execute this interactively:
```bash
set -Ux PYENV_ROOT $HOME/.pyenv
fish_add_path $PYENV_ROOT/bin
```
Otherwise, execute this snippet:
```bash
set -Ux PYENV_ROOT $HOME/.pyenv
set -U fish_user_paths $PYENV_ROOT/bin $fish_user_paths
```
Finally, add this to `~/.config/fish/config.fish`:
```bash
pyenv init - fish | source
```
---
#### Restart Your Shell
Regardless of which shell you are using, for the `PATH` changes to take effect, the shell must restart:
```bash
exec "$SHELL"
```
#### Install Python Build Dependencies
`pyenv` will try its best to download and compile the desired Python version. Still, sometimes the compilation fails because of unmet system dependencies, or the compilation succeeds but the new Python version exhibits strange failures at runtime. The following instructions are the developer's recommendations for a sane build environment.
Please only apply the following instructions for your OS and skip the others.
##### macOS (Homebrew)
If you haven't already done so, please install Xcode Command Line Tools (`xcode-select --install`) and [Homebrew](http://brew.sh/). Then run:
```bash
brew update
brew install openssl readline sqlite3 xz zlib tcl-tk@8
```
##### Debian / Ubuntu / Linux Mint (apt)
```bash
sudo apt update
sudo apt install build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev curl git \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
```
##### Fedora 22+ (dnf)
```bash
dnf install make gcc patch zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel tk-devel libffi-devel xz-devel libuuid-devel gdbm-libs libnsl2
```
##### Arch Linux (pacman)
```bash
pacman -S --needed base-devel openssl zlib xz tk
```
If your OS is not listed here, please see the [complete documentation of suggested build environments](https://github.com/pyenv/pyenv/wiki#suggested-build-environment) from the developers of `pyenv` itself.
---
#### List and Install Python Versions with `pyenv`
With your shell configured and Python build dependencies installed, let's now ask `pyenv` to list all Python versions it knows about. This is a long list, so you might want to use a regular expression to narrow it down.
In this case, we are asking for a list of all available Python versions from 3.12 to 3.14:
```bash
pyenv install --list | grep "3\\.1[234]"
```
Once you have found your desired version(s) of Python, it/they can be installed with a single command:
```bash
pyenv install 3.13.2 # installs Python version 3.13.2
pyenv install 3.9.17 # installs Python version 3.9.17
```
Allow the installation(s) to complete.
Repeat for additional Python versions if needed.
#### Verify Installation(s)
This command will list the versions of Python pyenv has access to on your system. It also tells you which version is currently used by default.
```bash
pyenv versions
```
The `*` indicates which version is set to run by default. For example:
```bash
* system (set by /path/to/your/.pyenv/version)
3.13.2
3.9.17
```
#### Set a Global or Local Python Version
If desired, you can make this new version of Python the global or local default.
```bash
pyenv global 3.13.2 # set a global default
# OR
pyenv local 3.9.17 # set for a specific project directory
```
Run `pyenv versions` again, and you will see the output has changed to your selected version of Python. For example:
```bash
system
* 3.13.2 (set by /path/to/your/.pyenv/version)
3.9.17
```
#### Return to System Python
If you want to return to your system's stock version of Python, just run:
```bash
pyenv global system
```
#### Uninstall a Particular Python Version
To remove a specific version of Python from `pyenv`, simply run:
```bash
pyenv uninstall 3.9.17 # to uninstall Python version 3.9.17
```
---
#### Use `venv` to Create Virtual Environments
Advantages of `venv` over the older `virtualenv` option:
- **Standard Library:** `venv` is part of the Python 3 standard library, so you don't need to install it separately.
- **Lightweight:** `venv` creates environments by creating symbolic links (or copying in some cases) to the base Python installation, making the environments smaller and faster to create than those of `virtualenv`, which often copies the entire Python interpreter into the virtual environment's directory.
- **Extensible:** `venv` environments can be extended and customized. You can use `pip` to install any packages you need.
- **Isolated:** `venv` provides proper isolation for your project's dependencies from other Python projects on your system.
- **Recommended:** It is the officially recommended method to create virtual environments in Python 3.
To create the virtual environment, navigate to your project directory:
```bash
cd /path/to/your/project
```
The command to create a new environment is as follows. This command will use the Python interpreter that `pyenv` has made active (either globally or locally) to create the environment.
For Linux and macOS, run:
```bash
python3 -m venv .venv[-optional-python-version-number]
```
This creates a new directory called `.venv-3.13.2` (for example) at the top level of your project. I like to add the Python version number after `.venv` so it is clear exactly which version of Python this virtual environment runs.
You can choose to name this directory anything you would like. But some variant of `.venv` is recommended.
---
#### Activate the Virtual Environment
From the project's root directory, run:
```bash
source [your-venv-directory]/bin/activate
```
And your terminal should indicate the environment is now active.
#### Install Python Packages
With your virtual environment activated, install any Python packages your project requires:
```bash
pip install # packages required for your project
```
As you install Python packages, they will only run while this virtual environment is active, effectively isolating your project dependencies from the rest of your system.
Proceed to build and test your Python program as normal.
#### Deactivate the Virtual Environment
When you are finished with your coding session, deactivate the virtual environment with this simple command:
```bash
deactivate
```
If needed, you can then switch to another virtual environment running a different version of Python and/or packages to see how these new environments affect your program.
#### Remove a Virtual Environment
Since we created the environment in a sub-directory of our project, simply delete the `.venv` directory to remove the virtual environment. For example:
```bash
rm -rf /path/to/your/project/.venv-3.9.17
```
#### Go Further with `venv`
For more information about using `venv`, I recommend starting with the official documentation: [venv - Creation of Virtual Environments - docs.python.org](https://docs.python.org/3/library/venv.html)
---
#### Basic Dependency Declaration with `pip`
Most Python programs make use of external packages and modules. To ensure your program has the correct version of everything it needs to run properly, it's a good idea to formally declare all dependencies in a way that can easily be updated and reproduced on another system or new virtual environment.
Fortunately, Python's standard package manager `pip` makes this easy.
#### Generate a `requirements.txt` File
After our packages are installed, all we need to do is use `pip` to generate a `requirements.txt` file. This file lists all the installed packages and their versions. To do this, run:
```bash
pip freeze > requirements.txt
```
Anytime your dependencies change, simply re-run the command above, and `requirements.txt` will update.
`requirements.txt` can then be used to install the correct version of all dependencies in a new virtual environment or on an entirely new system by running:
```bash
pip install -r requirements.txt
```
#### Set a Local Python Version
In most cases, it is also a good idea to require a specific version of Python to run your project. From your project's root directory, set this by running:
```bash
pyenv local 3.13.2 # replace with your desired Python version number
```
This creates a `.python-version` file which tells your system which version of Python to use.
---
#### In Summary
For managing multiple Python versions on your system while creating isolated development environments, using `pyenv` along with `venv` is the recommended and most straightforward approach. Once the virtual environment is running, using `pip` to create and update the `requirements.txt` file is a simple way to ensure all dependencies can easily be reproduced.
This guide has helped us create a simple, clean, and flexible virtual development environment.
If you found this helpful and would like me to write guides for more advanced dependency management with tools like [Poetry](https://python-poetry.org/) or [uv](https://docs.astral.sh/uv/), please contact me on Bluesky [@benjaminpatch.com](https://bsky.app/profile/benjaminpatch.com).
Thanks for reading and I wish you the best in creating and managing all of your Python virtual environments!
#### Additional Information and Sources
- [pyenv Documentation](https://github.com/pyenv/pyenv?tab=readme-ov-file#simple-python-version-management-pyenv)
- [pyenv Wiki](https://github.com/pyenv/pyenv/wiki)
- [Python Virtual Environments: A Primer - realpython.com](https://realpython.com/python-virtual-environments-a-primer/)
- [venv Documentation - python.org](https://docs.python.org/3/library/venv.html)
- [pip freeze - Python Packaging Authority](https://pip.pypa.io/en/stable/cli/pip_freeze/)
---
### The Journey of Artificial Intelligence
URL: https://benjaminpatch.com/posts/2024/Dec/18/journey-of-artificial-intelligence/
> AI has become a cornerstone of modern technology, impacting virtually every industry in today's economy. But how did we get here? Let's explore its fascinating history, from the coining of the term to the rise of machine learning, artificial neural networks, and generative AI.
Artificial intelligence (AI) has become a cornerstone of modern technology, impacting virtually every industry in today's economy. But how did we get here?
The journey of AI spans decades of experimentation, breakthroughs, and debates. Let's explore its fascinating history, from the coining of the term to the rise of machine learning, artificial neural networks, and generative AI.
#### Defining Intelligence
At its core, AI refers to systems that exhibit behavior that we would typically associate with human intelligence. However, defining human intelligence itself is a complex task. Intelligence manifests itself in a wide variety of forms such as artistic expression, mathematical prowess, and problem-solving skills just to name a few. Plus, there's no universal standard for measurement β making it difficult to definitively label a computer as "intelligent."
While computers excel at specific tasks like playing chess or recognizing patterns, they lack the general understanding and awareness that humans possess. They might be able to follow rules and algorithms flawlessly, but it's important to understand that even the most advanced AI systems at this time, do not grasp the purpose behind their actions.
#### Artificial Intelligence is Born
In 1955, the legendary computer scientist John McCarthy coined the term "artificial intelligence" to secure funding for the very first AI workshop. This event, held in 1956, aimed to explore whether computers could exhibit behaviors humans would consider intelligent.
Despite the limited computational power of the era, this workshop launched the field well beyond academics. The term "artificial intelligence" captured imaginations and inspired generations of scientists, writers, and technologists. Without McCarthy's vision and knack for branding, it's possible AI might have languished as an academic curiosity.
#### Early AI: Rules and Symbols
Early AI research was dominated by **symbolic reasoning**. Scientists like Allen Newell and Herbert Simon developed the "General Problem Solver," a program designed to solve problems expressed mathematically. Their work was rooted in the "Physical Symbol System Hypothesis," asserting that intelligence could emerge from linking symbolic representations.
This led to "expert systems" that could perform tasks like medical diagnosis or financial analysis by following pre-defined steps. However, they were limited by the sheer number of rules required to handle complex scenarios. A problem that became known as "combinatorial explosion."
#### From Symbols to Machine Learning
By the late 1980s, researchers realized symbolic reasoning had limits, especially in environments requiring adaptability. Enter **machine learning (ML)**, a paradigm shift that allowed computers to learn patterns from data rather than relying on predefined rules. This marked a turning point, where machines transitioned from rigid problem-solving to flexible learning.
One of the earliest successes in ML came in 1959 when Arthur Samuel developed a checkers-playing program that improved by playing against itself. This demonstrated that machines could "teach" themselves strategies, opening doors to more advanced applications. Samuel's program was a landmark, showing that AI could evolve beyond predefined knowledge to adapt and improve autonomously.
#### Neural Networks and Deep Learning
In the late 1980s, Geoff Hinton and others revitalized interest in **artificial neural networks**, an approach inspired by the human brain. These networks, organized in layers, excelled at identifying patterns in data. By the 1990s, advancements in **deep learning** introduced architectures with even more layers, enabling AI to tackle more complex tasks, from image recognition to natural language processing.
Deep learning's power lies in its ability to process massive datasets, identifying patterns beyond human perception. For instance, Google's DeepMind famously defeated the world champion of Go, a game far more complex than chess, by leveraging deep learning to analyze millions of potential moves. This victory highlighted how AI could master tasks previously thought too intricate for machines, reshaping industries like gaming, healthcare, and logistics.
Deep learning also benefited from advancements in hardware, particularly GPUs, which greatly accelerated computation. Coupled with the explosion of available data on the internet, neural networks have become a dominant force in AI research and applications.
#### Big Data Fuels AI's Growth
The rapid progress of AI over the last two decades owes much to the explosion of Big Data and the rise of data science. Massive datasets, generated from social media, sensors, e-commerce, and more, provide the raw material needed for AI systems to learn and improve. These datasets allow machine learning models to uncover patterns and make predictions with unprecedented accuracy.
However, managing Big Data poses its own challenges. Collecting, storing, and processing such enormous datasets require robust infrastructure and advanced tools. Organizations increasingly use cloud platforms and distributed computing frameworks to handle the scale and complexity of Big Data effectively.
#### The Role of Data Science
Data science bridges the gap between raw data and actionable insights. Combining statistics, computer science, and domain expertise, data scientists analyze and preprocess data to make it usable for AI applications. They clean datasets, identify trends, and engineer features that enhance the performance of machine learning models.
Data science also plays a crucial role in interpreting the results of AI models. For example, while an AI system might identify a correlation between specific behaviors and purchasing decisions, it's often up to data scientists to contextualize these findings and derive meaningful business strategies.
Together, Big Data and data science have **enabled AI to move from theoretical possibilities to practical applications** that impact daily life.
#### Generative AI: Machines That Create
While traditional AI focuses on analyzing data, generative AI takes it a step further by creating new content. Systems like **large language models (LLMs)** and **generative adversarial networks (GANs)** can produce text, code, images, music, and even video. These advancements hinge on foundational models β massive networks trained on diverse datasets β and techniques like self-supervised learning, which labels data autonomously.
Generative AI represents a significant leap forward, blurring the lines between human creativity and machine capability. Applications like OpenAI's GPT and DALLβ’E have demonstrated AI's ability to write stories, generate artwork, and even assist in scientific discovery. However, it also raises [ethical questions](/posts/2024/Dec/11/responsible-ai-ethical-principles-for-humanity/) about authenticity, bias, and the role of humans in creative industries.
This technology's potential is immense but must be approached cautiously. For instance, deepfake technology, a byproduct of generative AI, has sparked concerns about misinformation and privacy. Policymakers, technologists, and ethicists are now grappling with how to ensure these tools are used responsibly.
#### Lessons from AI's History
The evolution of AI underscores the importance of adapting to new challenges and opportunities:
- **Early Days:** Symbolic reasoning laid the groundwork but struggled with real-world complexity. These early systems were limited to structured environments like games and predefined problem sets.
- **Machine Learning:** Enabled AI to learn from data, bypassing the rigidity of rule-based systems. This adaptability marked a significant shift, allowing AI to tackle broader applications.
- **Deep Learning:** Leveraged massive datasets to tackle tasks once thought impossible for machines. Advances in hardware and data accessibility have supercharged this field, enabling breakthroughs in fields ranging from medicine to entertainment.
#### Closing Thoughts
As AI continues to evolve, its history offers a valuable perspective on innovation. By appreciating the breakthroughs and setbacks of the past, we can better navigate the ethical and practical challenges of tomorrow. Whether it's a chess game or a generative AI model writing poetry, the story of AI is, at its core, a reflection of humanity's drive to understand and innovate.
Moreover, this journey reminds us that AI's success has always depended on human vision and creativity. As we look ahead, it's not just about building smarter machines but about ensuring they serve humanity's best interests, fostering collaboration, and unlocking new frontiers of possibility.
#### Additional References and Sources
- [Wikipedia article on artificial intelligence](https://en.wikipedia.org/wiki/Artificial_intelligence)
- [Stanford Encyclopedia of Philosophy article on intelligence](https://plato.stanford.edu/entries/artificial-intelligence/)
- [Dartmouth Summer Research Project on Artificial Intelligence](https://en.wikipedia.org/wiki/Dartmouth_Summer_Research_Project_on_Artificial_Intelligence)
- [John McCarthy]()
- [General Problem Solver](https://en.wikipedia.org/wiki/General_Problem_Solver)
- [Physical Symbol System Hypothesis](https://ai.stanford.edu/~nilsson/OnlinePubs-Nils/PublishedPapers/pssh.pdf)
- [Expert systems](https://en.wikipedia.org/wiki/Expert_system)
- [Arthur Samuel]()
- [Artificial neural network](https://en.wikipedia.org/wiki/Artificial_neural_network)
- [Deep learning](https://en.wikipedia.org/wiki/Deep_learning)
- [Geoffrey Hinton](https://en.wikipedia.org/wiki/Geoffrey_Hinton)
- [Generative Adversarial Network](https://en.wikipedia.org/wiki/Generative_adversarial_network)
---
### Responsible AI: Ethical Principles for Humanity
URL: https://benjaminpatch.com/posts/2024/Dec/11/responsible-ai-ethical-principles-for-humanity/
> In this brief but eye-opening exploration of responsible AI, you'll discover the critical ethical challenges facing our technological future. More than a cautionary tale, this article offers a roadmap for developing AI that amplifies human potential while safeguarding our fundamental values.
In this brief but eye-opening exploration of responsible AI, you'll discover the critical ethical challenges facing our technological future. More than a cautionary tale, this article offers a roadmap for developing AI that amplifies human potential while safeguarding our fundamental values.
Whether you're a technologist, business leader, or simply someone curious about the profound impact of AI, you'll gain insights into how we can harness this revolutionary technology with wisdom, fairness, and foresight.
#### The Imperative of Responsible AI
Artificial intelligence (AI) accelerated by machine learning (ML) is transforming our world at breathtaking speed, promising breakthroughs in medicine, science, and industry. While I am inspired by the current and near-future potential of AI technology, I am also deeply concerned about the speed and direction we are traveling.
The promise of artificial intelligence is staggering β imagine systems that can diagnose diseases earlier than human physicians, optimize complex global supply chains, or solve intricate scientific challenges that have long eluded human comprehension. Yet, this extraordinary potential comes with equally profound responsibilities.
Science fiction is filled with warnings of how unchecked technological development can lead to unintended consequences β and AI powered by machine learning is no longer confined to the safety of science fiction. Machine learning has become a powerful lens that can either amplify our collective human potential or exacerbate existing societal inequities. Responsible AI development is our critical checkpoint β ensuring that technological advancement serves humanity's broader interests.
#### Real-World Stakes of Algorithmic Bias
The algorithmic bias of machine learning is not a theoretical problem β it's a present-day reality with tangible human consequences. Here are a few real-world examples I found in my research:
- **Amazon's recruiting algorithm** (now scrapped) was proven to discriminate against female applicants (source: [Reuters](https://www.reuters.com/article/world/insight-amazon-scraps-secret-ai-recruiting-tool-that-showed-bias-against-women-idUSKCN1MK0AG/)).
- **ChatGPT-4** recommends fewer MRIs and stress tests for Black patients and female cardiology patients without sound medical reasoning (source: [CBS News](https://www.cbsnews.com/sanfrancisco/news/ai-chatbots-are-supposed-to-improve-health-care-but-research-says-some-are-perpetuating-racism-2/)).
- **Credit scoring ML algorithms** routinely discriminate based on non-financial attributes like race and sex (source: [Springer Nature](https://link.springer.com/article/10.1007/s00146-023-01676-3)).
- Among dozens of other examples cited by [The Brookings Institution](https://www.brookings.edu/articles/algorithmic-bias-detection-and-mitigation-best-practices-and-policies-to-reduce-consumer-harms/) and many other credible research groups.
The evidence is clear and deeply troubling. Machine learning systems have already inadvertently perpetuated discriminatory practices across many aspects of modern society. Hence, our imperative need for more ethically responsible AI development.
#### Workforce Disruption and Economic Recalibration
Machine learning will continue to fundamentally reshape our economic landscape. Not just by incremental changes but a potential restructuring of entire industries. Automation driven by AI could displace millions of jobs, particularly in sectors like manufacturing, transportation, customer service, and administrative work. Generative AI threatens creative fields such as writing, graphic design, video editing, and yes, even entry-level software developers β virtually all knowledge-based work could be at risk. Each worker can be empowered to do so much more, but fewer workers might be needed overall.
However, this isn't simply a narrative of job loss. We're also witnessing the emergence of entirely new job categories that didn't exist a few years ago, such as AI prompt engineering. Therefore, I strongly believe the key is **proactive adaptation** β investing in reskilling programs, creating educational frameworks that prepare workers for an AI-integrated workforce, and developing policies that ensure economic transitions are equitable and supportive. If political leaders fail to deliver such adaptive programs and policies, it will likely lead to economic blowback not seen in generations.
#### Core Principles of Responsible AI
To protect against the many potential harms of AI, [Atlassian](https://www.atlassian.com/blog/artificial-intelligence/responsible-ai) and many other industry leaders advocate that four key principles must guide every project claiming to operate under the banner of ethically responsible AI:
1. **Transparency:** AI must be explainable. Stakeholders should understand how decisions are made, and developers should document and share the inner workings of their systems. A lack of transparency can lead to mistrust and misuse.
2. **Fairness:** Bias in AI systems is one of the biggest ethical challenges. Developers need to carefully evaluate training datasets and outcomes to ensure algorithms don't disproportionately harm or exclude certain groups. Regular audits can help identify and address potential issues.
3. **Privacy and Security:** As AI often relies on vast amounts of sensitive data, privacy and security should be top priorities. Encryption, anonymization, and secure coding practices are essential for safeguarding user information and preventing breaches.
4. **Accountability:** Every AI decision should have a human touchpoint. When errors occur, there should be a clear chain of accountability to rectify problems quickly and learn from mistakes.
#### Key Considerations for Project Stakeholders
Stakeholders have a unique responsibility to champion ethically responsible AI initiatives. Here's how I suggest they contribute:
- **Promote human oversight:** Ensure there are checks and balances in place, especially for high-stakes decisions like loan approvals or medical diagnoses.
- **Assess societal impact:** Go beyond profit to consider how your AI solutions affect communities.
- **Champion diversity:** Building diverse teams helps mitigate bias and ensures your AI reflects a broader range of perspectives.
#### Best Practices for Developers
For software developers, responsible AI starts with adopting tools and frameworks designed to uphold ethical standards.
- **Follow ethical AI guidelines:** Frameworks from companies like [Microsoft](https://www.microsoft.com/en-us/ai/responsible-ai) and [Google](https://ai.google/responsibility/principles/) can serve as roadmaps for creating trustworthy systems.
- **Use bias detection tools:** Open-source resources like [IBM's AI Fairness 360](https://aif360.res.ibm.com/) toolkit can help developers identify and reduce bias in datasets and models.
- **Test and document rigorously:** Regular testing and thorough documentation are vital for ensuring transparency, fairness, and accountability.
#### Responsible AI in Action
Here are two quick examples of how ethically responsible AI development can be put into practice:
##### Case Study 1: Reducing Bias in Hiring
A tech company used an AI tool for candidate screening but discovered it favored male applicants due to historical bias in the data. By retraining the model on a more diverse dataset and introducing oversight checks, the company created a fairer hiring process.
##### Case Study 2: Transparent Diagnostics in Healthcare
A healthcare provider implemented an AI diagnostic tool with clear explanations for its decisions. Doctors could review the system's recommendations, enhancing trust and enabling better patient care.
#### A Personal Call to Action
To my fellow technologists, policymakers, and innovators: we stand at a critical juncture. The AI and machine learning systems we develop today will shape human experiences for generations. Our choices matter β profoundly and irrevocably.
Responsible AI is not about constraining innovation but channeling it toward meaningful, equitable outcomes. We must approach this technology with humility, foresight, and an unwavering commitment to human dignity.
The future of artificial intelligence is not predetermined. It will be shaped by our collective choices, our ethical frameworks, and our willingness to prioritize human well-being over technological expediency.
My personal commitment to ethically responsible AI development will remain a strong guiding principle as I develop real-world applications and training materials alike. I strongly encourage you to do the same and draw attention to oversights you might be exposed to. Our future can be extraordinarily bright so long as we develop AI responsibly today.
What are your thoughts on responsible AI development? Please share your thoughts with me on Bluesky [@benjaminpatch.com](https://bsky.app/profile/benjaminpatch.com). Thanks for reading and please code responsibly.
#### Additional References and Sources
- [What is Responsible AI - Azure Machine Learning](https://learn.microsoft.com/en-us/azure/machine-learning/concept-responsible-ai?view=azureml-api-2)
- [Building a responsible AI: How to manage the AI ethics debate](https://www.iso.org/artificial-intelligence/responsible-ai-ethics)
- [Responsible AI: Key Principles and Best Practices](https://www.atlassian.com/blog/artificial-intelligence/responsible-ai)
- [What is Data Bias?](https://www.ibm.com/think/topics/data-bias)
## Links
- [About](https://benjaminpatch.com/about/)
- [Atom Feed](https://benjaminpatch.com/feeds/all.atom.xml)
- [LinkedIn](https://www.linkedin.com/in/benjaminpatch/)
- [Bluesky](https://bsky.app/profile/benjaminpatch.com)
- [GitHub](https://github.com/dev-patch17)