Member-only story
12 Examples To Understand Python User-Defined Functions
Everything from syntax, documentation, parameters, and arguments to local and global variables
Hello, and welcome to my guide to Python user-defined functions. This article will cover the basics of Python user-defined functions, the syntax you must master, and examples to help you consolidate your newly acquired knowledge.
Introduction
In simple terms, a function takes an input, performs a computation, and produces an output. Python has user-defined functions, anonymous functions, and built-in functions, such as the print()
function. I’m sure you will all recognise the print()
function as your introductory line of code to the wonderful world of programming.
print("Hello World")
>>> Hello World
Today, however, we are going to focus on user-defined functions. In programming, you will eventually reach a point where you are regurgitating the same code over and over. This is time-consuming and unnecessarily repetitive. In programming, there is an acronym for this: DRY (don't repeat yourself)! To avoid this you can define your own functions. This will help make your code organised, manageable, and re-usable. The idea is that instead of writing the same code again and again for different inputs, you can call (use) your functions when necessary.

The syntax is the set of rules that defines code (in this case, your function).
The first line (header)
- the keyword
def
- the function name (keep it relevant — link to naming conventions)
- parentheses
()
, which may or may not include parameters and arguments - and a colon
:
Function/statement block (body)
- The following lines of the function block include what the function is supposed to do. All these lines have to be indented (press Tab).
- The first statement of a function can be an optional statement…