Functions

In programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later you can “call” the function by name and Python executes that sequence wherever the call appears.

Built-in Functions

Python ships with many useful functions. You have already been using some:

len(inventory)           # number of items
max(scores)              # highest score
min(distances)           # nearest enemy
type(player_speed)       # <class 'float'>

Type conversion functions are essential when mixing numbers and strings:

health_str = str(health)     # int → string for display
bonus      = int("50")       # string → int from a config file
ratio      = float(hits) / total

int() truncates rather than rounds: int(3.99) gives 3.

Defining New Functions

Use the def keyword to create your own function:

def respawn_player():
    player.set_pos(SPAWN_X, SPAWN_Y, SPAWN_Z)
    player.health = 100

The first line is the header — it must end with a colon. Everything indented beneath it is the body — the statements that run when the function is called. The body is not executed when the definition is read; it only runs when the function is called:

respawn_player()

Parameters and Arguments

Parameters are the variables listed in the function definition. Arguments are the actual values passed when calling the function:

def take_damage(amount):      # 'amount' is the parameter
    player.health -= amount
    if player.health <= 0:
        game_over()

take_damage(25)               # 25 is the argument

You can provide default values for optional parameters:

def spawn_enemy(x, y, z, enemy_type="goblin"):
    ...

spawn_enemy(10, 0, 5)              # uses default "goblin"
spawn_enemy(50, 0, 5, "dragon")    # explicit type

Fruitful and Void Functions

A fruitful function returns a value using the return statement:

def calculate_damage(attack_power, defense):
    raw = attack_power - defense
    return max(0, raw)    # never negative

final_damage = calculate_damage(40, 15)
take_damage(final_damage)

A void function performs an action but returns nothing. If you try to use its result it gives back the special value None:

result = respawn_player()
print(result)    # None

Always capture the return value of fruitful functions in a variable or use it directly in an expression. If you write calculate_damage(40, 15) on a line by itself, the return value is computed and then immediately discarded.

Flow of Execution

Python reads a script from top to bottom. A function definition is processed but not executed — the body only runs when the function is called. A function must be defined before it can be called.

When a function is called, execution “detours” into the function body, runs all its statements, then returns to where the call was made. One function can call another, and Python keeps track of all the detours.

Scope

Variables created inside a function exist only inside that function — this is called local scope. Once the function returns they are gone.

def calculate_damage(attack, defense):
    raw = attack - defense       # 'raw' exists only here
    return max(0, raw)

The variable raw is invisible outside the function. This is a feature: functions can use any variable names they like without interfering with each other.

If you need to modify a value that lives outside all functions (at module level), declare it with global. In practice it is almost always cleaner to store shared state on an object (see Classes and Objects) rather than using globals.

Why Functions?

  • Name a group of statements — makes code easier to read and debug.

  • Eliminate repetition — change the behaviour once, in one place.

  • Break the problem into pieces — debug each piece independently.

  • Reuse across programs — a well-written calculate_damage function can work in any game project.

The Acron task system is built on exactly this idea: you write a function that handles one concern (move the camera, check collisions, update the HUD) and register it with the engine, which calls it at the right time.