14.1. Function Definition

  • Automate repetitive tasks

  • Allow code reuse

  • Improve code readability

  • Clean-up code

  • Allow easier refactoring

function
func
fn

A set of instructions which has common name. Function will execute all of those instructions each time it is called.

call
function call
call a function

Run a function.

procedure

The same as function. Way back in history there was a distinction that the procedures don't take an arguments and functions does. Now this blurred completely. Hardly anyone is talking about procedures now, so the same stuck, but it is very rarely used. Most common old-school programmers whill use that word. You may find this also in documentation of aged projects.

Syntax:

def <name>():
    ...

Example:

>>> def say_hello():
...     print('hello')

14.1.1. Definition

  • Function is defined using def keyword

  • Function name is followed by parentheses

  • Colon : is required at the end of the line

  • Function body is indented

  • Avoid one-liners

>>> def say_hello():
...     print('hello')

If the function is short, you can also write it in the one line. This is not recommended and degrades code readability:

>>> def say_hello(): print('hello')

14.1.2. Calling

Let's define a function:

>>> def say_hello():
...     print('hello')

Call a function for a first time:

>>> say_hello()
hello

Call a function for a second time:

>>> say_hello()
hello

Each time it will give the same result. That's right. This function is very simple and all what it does is just print word 'hello' on the standard output.

14.1.3. Pass keyword

  • Use pass keyword to define empty function

>>> def say_hello():
...     pass

14.1.4. Function Name Case

  • Use snake_case

  • Do not use camelCase

  • Do not use PascalCase

Use snake_case names in Python. It is easy to remember. Python looks like a snake, and sounds like a snake ;) This is double internal joke, because Python name came from Monty Python, of which Guido van Rossum was a big fun.

This is snake_case() name. It is Pythonic way:

>>> def say_hello():  # good
...     pass

Do not use camelCase names:

>>> def sayHello():  # bad
...     pass

The camelCase name is c/c++/Java/JavaScript convention. It is not good to mix conventions from different languages. If you write C code, use C conventions. If you program in Python, use Python conventions. Remember, there are different communities around both of those languages:

Do not use PascalCase names:

>>> def SayHello():  # very bad
...     pass

The PascalCase name has completely different meaning in Python - it is used for classes. Using such name convention will mistake others.

14.1.5. Convention

  • Use good and descriptive names

  • Follow convention (such as web, data science, machine learning)

People, especially those who uses simple IDEs or notepads without sophisticated autocompletion will tend to create function with shorter names in order to save couple of characters each time when it is called. This at the beginning could be a good idea, but in the long run will lead to disaster. Coming back to your code after a year or two will require you to rediscover the code and read it once again.

>>> def var(data, m):
...     return sum((Xi-m) ** 2 for Xi in data) / len(data)
>>>
>>> var([1,2,3,4], 1)  
>>> vars([1,2,3,4])  

Function name var() is very similar to built-in function vars() which does something completely different. It shows all the attributes of an object passed to it. A single misspell, such as forgetting about letter s at the end of a name may lead to printing all the internal information about object publicly. This is very dangerous for publicly accessed systems.

More verbose names, such as variance() will distinguish this function from built-in vars() far better:

>>> def variance(data, m):
...     return sum((Xi-m) ** 2 for Xi in data) / len(data)
>>>
>>> variance([1,2,3,4], 1)  
>>> vars([1,2,3,4])  

This way a probability for mistake is far lower and even if, then will be better discoverable.

14.1.6. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Definition Define
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Define function `say_hello`
# 2. Function prints 'hello world' on screen
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `say_hello`
# 2. Funkcja wypisuje 'hello world' na ekranie
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

>>> assert isfunction(say_hello), \
'Object `say_hello` must be a function'

>>> say_hello()
hello world
"""

# Define function `say_hello`
# Function prints 'hello world' on screen
# type: Callable[[], None]
...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Definition Call
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% English
# 1. Call function `run` three times
# 2. Do not use loop or comprehension
# 3. Run doctests - all must succeed

# %% Polish
# 1. Wywołaj funkcję `run` trzy razy
# 2. Nie używaj pętli ani rozwinięcia
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

>>> assert isfunction(run), \
'Object `run` must be a function'

>>> content = open(__file__).read()
>>> content.count('run'+'()') - 1
3
"""

def run():
    print('Beetlejuice')


# Call function `run` three times
# Do not use loop or comprehension
# type: None
...