Python Functions for Games

Learn Python functions by writing game helpers: def, parameters, return values, and why splitting a game into small functions makes it easier to test.

A function is a named block of code you can run whenever you need it. Good games are built from small functions like show_board(), winner() and computer_move(). Every challenge on this site asks you to write one, because a function can be tested on its own.

example 1 · press Run, then edit and run again

return sends a value back

print() only shows a value; return hands it back to the code that called the function, so you can store it, compare it or pass it on.

example 2 · press Run, then edit and run again

Parameters and defaults

example 3 · press Run, then edit and run again

Why functions make games easier

💡 A function that should give back a value but has no return gives back None. That's the most common function bug.

Games that use Functions

Practise this with 10 of the 20 games:

Frequently asked questions

What is the difference between print and return?

print shows text on the screen. return gives a value back to the caller so the program can use it. A function can do both.

Can a Python function return more than one value?

Yes: return a, b sends back a tuple, and you can unpack it with x, y = my_function().

More Python concepts