Learning LibraryCore Coding LibraryTeens

Return Values in Python: functions that hand back answers

A function that just acts is useful; a function that answers is powerful. return turns a function into a question you can ask — like did this laser hit that enemy?

The big idea

return immediately ends a function and sends a value back to whoever called it.

See it in code

1The basics

return sends a value back to whoever called the function. score_for takes a hit count, multiplies by 100, and returns the result — so print can show it:

python
def score_for(hits):
    return hits * 100

print(score_for(3))
Run it — the function hands back a number:
300

return hits * 100 computed 300 and passed it out. The caller decides what to do with it — print it, store it, add it to a total.

2A step further

A function can return a True/False answer — turning it into a question you ask. is_alive returns whether health is above zero:

python
def is_alive(health):
    return health > 0

print(is_alive(20))
print(is_alive(0))
Run it — the function answers True or False:
True
False

The returned boolean drops straight into an if. That's the pattern behind every collision, win, and game-over check.

3In our world

Same idea with real game objects. is_hit takes a laser and an enemy and returns the boolean from laser.hits(...). The caller gets back True or False and decides what to do — score, remove, ignore:

python
from game import Enemy, Laser

def is_hit(laser, enemy):
    return laser.hits(enemy)

enemy = Enemy(240, 300)
near = Laser(240, 300)
far = Laser(240, 100)

print("Near laser hits?", is_hit(near, enemy))
print("Far laser hits?", is_hit(far, enemy))
Run it — the function answers each collision question:
Near laser hits? True
Far laser hits? False

is_hit hands back a boolean, so the caller can drop it straight into an if. A function can return anything — a number, a string, a list, an object — and return stops the function the instant it runs.

The same idea, everywhere

Returning a value is how you build a toolbox of reusable answers: moving_average(prices) returns a number, reverse_complement(dna) returns a string, spawn_wave(n) returns a list. Small functions that each return one clear result compose into big programs.

Try it yourself

Add an early return False when the enemy is already off-screen, before the collision check — notice how return can exit early. Then write distance(a, b) that returns how far apart two entities are.

The common mistake

Forgetting the return, or putting code after it. A function with no return hands back None, so is_hit(...) would always look false. And any line after a return that runs is dead code — return exits immediately.

What it unlocks

Returned answers make functions composable, feed conditionals, and raise the question of scope — where the returned value's variables lived.

Want the simpler version? Read the Kids version →