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.
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.
Parameters and defaults
Why functions make games easier
- You can test one piece (does
winner()spot diagonals?) without playing a whole game. - Names explain what code does:
if crashed(head, snake):reads like English. - You can reuse them: the same
winner()helps the computer choose its move.
💡 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:
- #01☆☆☆
Tic Tac Toe in Python
Learn Lists, Functions and if, elif and else.
- #03☆☆☆
Snake Game in Python (Turtle)
Learn Turtle graphics, Lists and Functions.
- #06☆☆☆
Pong-Style Paddle Game in Python
Learn Turtle graphics, Functions and if, elif and else.
- #09☆☆☆
Connect Four-Style Game in Python
Learn 2D lists and grids, Lists and Functions.
- #10☆☆☆
Minesweeper-Style Game in Python
Learn 2D lists and grids, Functions and for loops.
- #11☆☆☆
Sudoku in Python
Learn 2D lists and grids, Functions and for loops.
- #13☆☆☆
Maze Game in Python
Learn 2D lists and grids, Functions and Lists.
- #14☆☆☆
Higher or Lower Game in Python
Learn The random module, while loops and if, elif and else.
- #19☆☆☆
Math Quiz Game in Python
Learn The random module, Dictionaries and for loops.
- #20☆☆☆
Typing Speed Game in Python
Learn Strings, Functions and for loops.
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().