Python for AIPython for AI
Building Programs

Organizing code

Split code into reusable functions

As your Python programs grow, keeping your code neat and understandable becomes really important. Let's look at how to organize your code effectively.

Why organize your code?

Imagine writing a recipe. If all the steps and ingredients are jumbled together, it's hard to follow. Code is similar! Organized code is easier to read, understand, and fix.

  • Readability: You (and others) can quickly understand what each part does.
  • Maintainability: Finding and fixing bugs is simpler.
  • Reusability: You can use parts of your code in different projects without rewriting them.

Creating helper functions

A function is a block of organized, reusable code that performs a single, related action. When you write a function, you give it a name. You can then "call" that name whenever you want to run that block of code.

Let's say you're building a simple game. You might have a line of code that checks if a player has enough points for an upgrade. This check might happen in several places. Instead of writing the same check over and over, you can put it in a function.

python
def check_points(player_score, cost):
    if player_score >= cost:
        return True
    else:
        return False

Using your functions

Once you define a function, you can use it by calling its name and providing any necessary arguments. This makes your main program much cleaner.

python
player_score = 1500
upgrade_cost = 1000

if check_points(player_score, upgrade_cost):
    print("Upgrade successful!")
else:
    print("Not enough points.")

another_upgrade_cost = 2000
if check_points(player_score, another_upgrade_cost):
    print("Could buy another upgrade.")
else:
    print("Still need more points for the next upgrade.")

Notice how much easier it is to see what's happening at a glance compared to repeating the if player_score >= cost logic every time.

How imports work

As your program grows, you might want to put related functions into separate files. This keeps each file focused on a specific task. When you want to use functions from another file, you use the import statement.

Imagine you have a file named game_logic.py that contains our check_points function. In another file, say main_game.py, you can bring in that function.

python
# game_logic.py
def check_points(player_score, cost):
    if player_score >= cost:
        return True
    else:
        return False
python
# main_game.py
from game_logic import check_points

player_score = 1500
upgrade_cost = 1000

if check_points(player_score, upgrade_cost):
    print("You can make the purchase!")

What you've accomplished

You've taken a big step in writing better code! By using functions and organizing them into separate files with imports, your programs will be much easier to manage, read, and build upon. This is a fundamental skill for any programmer.