what is a function?

A function is code that is callable, this means I can write code to do something one time, and call the name for it to do that thing at a different time from when I write it.

functions can make code simpler, easier to read, test, reuse, maintain and improve - all the good things.


how to make a function

functions are made with

  • the def keyword

  • a name

  • parentheses and a colon at the end

  • the code that makes up the function (its body) comes after the colon

def name_of_function():
    the body of the function
    ...

preview

I have these tests by the end of the chapter

functions/tests/test_functions.py
 1def test_making_a_function_w_pass():
 2    def w_pass():
 3        pass
 4
 5    assert w_pass() is None
 6
 7
 8def test_making_a_function_w_return():
 9    def w_return():
10        return
11
12    assert w_return() is None
13
14
15def test_making_a_function_w_return_none():
16    def w_return_none():
17        return None
18
19    assert w_return_none() is None
functions/tests/test_functions.py
22def test_what_happens_after_functions_return():
23    def return_leaves_the_function():
24        return None
25        return 'only one way for this line to run'
26
27    assert return_leaves_the_function() is None
28
29
30def test_constant_function():
31    def constant():
32        return 'the same thing'
33
34    assert constant() == 'the same thing'
35
36
37# Exceptions seen
38# AssertionError
39# NameError
40# TypeError

questions about functions


start the project

  • I name this project functions

  • I open a terminal

  • I use uv to make a directory for the project and initialize it

    terminal
    uv init functions
    

    the terminal shows

    Initialized project `functions`
    at `.../pumping_python/functions`
    

    then goes back to the command line.

  • I change directory to the project

    terminal
    cd functions
    

    the terminal shows I am in the functions folder

    .../pumping_python/functions
    
  • I make a directory for the tests

    mkdir tests
    

    the terminal goes back to the command line.

  • I make the tests directory a Python package

    Danger

    use 2 underscores (__) before and after init for __init__.py not _init_.py

    touch tests/__init__.py
    
    New-Item tests/__init__.py
    

    the terminal goes back to the command line.

  • I make an empty file for the tests in the tests folder

    touch tests/test_functions.py
    
    New-Item tests/test_functions.py
    

    the terminal goes back to the command line.

  • I open test_functions.py from the tests folder

  • I add the first failing test to test_functions.py

    1def test_failure():
    2    assert False is True
    
  • I go back to the terminal

  • I use echo to add pytest to requirements.txt

    echo "pytest" > requirements.txt
    
  • I add pytest-watcher to the requirements file

    echo "pytest-watcher" >> requirements.txt
    

    the terminal goes back to the command line.

  • I use Out-File to add pytest to requirements.txt

    "pytest" | Out-File requirements.txt -Encoding UTF8
    
  • I add pytest-watcher to the requirements file

    "pytest-watcher" >> requirements.txt
    
  • I use uv to install pytest-watcher with the requirements file

    terminal
    uv add --requirement requirements.txt
    

    the terminal shows that it installed pytest-watcher and its dependencies.

  • I add the new files and folders to git for tracking

    terminal
    git add .
    

    the terminal goes back to the command line.

  • I add a git commit message

    terminal
    git commit --all --message 'setup project'
    

    the terminal shows a summary of the changes then goes back to the command line.

  • I use pytest-watcher to run the tests automatically

    terminal
    uv run pytest-watcher . --now --patterns "**/*.py"
    

    the terminal is my friend, and shows AssertionError

    terminal
    ======================== FAILURES ========================
    ______________________ test_failure ______________________
    
        def test_failure():
    >       assert False is True
    E       assert False is True
    
    test_functions.py:2: AssertionError
    ================ short test summary info =================
    FAILED test_functions.py::test_failure - assert False is True
    =================== 1 failed in X.YZs ====================
    

    because False is NOT True

    if the terminal does not show the same error, then check if

    • your tests/__init__.py has two underscores (__) before and after init for __init__.py not _init_.py

    • you ran echo "pytest-watcher" >> requirements.txt, to add pytest-watcher to the requirements file

    and try uv run pytest-watcher . --now --patterns "**/*.py" again

  • I add AssertionError to the list of Exceptions seen, in test_functions.py

    1def test_failure():
    2    assert False is True
    3
    4
    5# Exceptions seen
    6# AssertionError
    
  • I change True to False in the assertion

    1def test_failure():
    2    # assert False is True
    3    assert False is False
    4
    5
    6# Exceptions seen
    7# AssertionError
    

    the test passes.


test_making_a_function_w_pass

The simplest function I can make is with the pass keyword.


RED: make it fail


  • I change test_failure to test_making_a_function_w_pass

    1def test_making_a_function_w_pass():
    2    w_pass
    3
    4
    5# Exceptions seen
    6# AssertionError
    

    the terminal is my friend, and shows NameError

    >       w_pass
    E       NameError: name 'w_pass' is not defined
    

    because Python does not know what I mean by w_pass since I do not have a definition for it in test_functions.py.

  • I add NameError to the list of Exceptions seen


what is a variable?

I can define a name in Python with a variable. A variable is a name that is used to point to an object. For example, in Mathematics we use x for any number.

Every time I use the name, Python uses the object I pointed the name to.


GREEN: make it pass


I change w_pass to a variable by pointing it to None (the simplest object)

1def test_making_a_function_w_pass():
2    # w_pass
3    w_pass = None
4
5
6# Exceptions seen
7# AssertionError
8# NameError

the test passes.


REFACTOR: make it better



how to call a function

I can call a function by placing parentheses (()) to the right of the name when I use it after it is defined.

name_of_function()

A call to a function gets the output of the function

name_of_function() -> output_object

RED: make it fail



GREEN: make it pass



REFACTOR: make it better


  • I remove the commented lines

     1def test_making_a_function_w_pass():
     2    def w_pass():
     3        pass
     4
     5    assert w_pass() is None
     6
     7
     8# Exceptions seen
     9# AssertionError
    10# NameError
    11# TypeError
    
  • I open another terminal then change directory to functions

    cd functions
    
  • I add a git commit message

    terminal
    git commit --all --message \
    'add test_making_a_function_w_pass'
    

    the terminal shows a summary of the changes then goes back to the command line.

I can make a function with pass.


test_making_a_function_w_return

I can also make a function with a return statement.


RED: make it fail


  • I go back to the terminal where the tests are running

  • I add a new test with w_return

     1def test_making_a_function_w_pass():
     2    def w_pass():
     3        pass
     4
     5    assert w_pass() is None
     6
     7
     8def test_making_a_function_w_return():
     9    w_return
    10
    11
    12# Exceptions seen
    

    the terminal is my friend, and shows NameError

    >       w_return
    E       NameError: name 'w_return' is not defined
    

    because Python does not know what I mean by w_return since I do not have a definition for it in test_functions.py.


GREEN: make it pass


I change w_return to a variable by pointing it to None (the simplest object)

 8def test_making_a_function_w_return():
 9    # w_return
10    w_return = None
11
12
13# Exceptions seen

the test passes.


REFACTOR: make it better



the return statement

The return keyword is used to define what a function gives as output when it is called.

functions are made with

def name_of_function():
    the body of the function
    return
  • I change pass to a return statement with the return keyword

  • I remove the commented lines

     1def test_making_a_function_w_pass():
     2    def w_pass():
     3        pass
     4
     5    assert w_pass() is None
     6
     7
     8def test_making_a_function_w_return():
     9    def w_return():
    10        return
    11
    12    assert w_return() is None
    13
    14
    15# Exceptions seen
    
  • I add a git commit message in the other terminal

    terminal
    git commit --all --message \
    'add test_making_a_function_w_return'
    

    the terminal shows a summary of the changes then goes back to the command line.

I can make a function with a return statement.

I have two functions with different statements, and the tests show that they both return None

def w_pass():
    pass
def w_return():
    return

their contents are different, their results are the same because “all functions return None by default, as if they have an invisible line that says return None”, which leads me to the next test.


test_making_a_function_w_return_none

I can make a function with a return statement that says exactly what the function returns.

def name_of_function():
    the body of the function
    return output

RED: make it fail


  • I go back to the terminal where the tests are running

  • I add a test with w_return_none

    the terminal is my friend, and shows NameError

    NameError: name 'w_return_none' is not defined
    

    because Python does not know what I mean by w_return_none since I do not have a definition for it in this file.


GREEN: make it pass


I change w_return_none to a variable by pointing it to None (the simplest object)

15def test_making_a_function_w_return_none():
16    # w_return_none
17    w_return_none = None
18
19
20# Exceptions seen

the test passes.


REFACTOR: make it better


I can make a function with return None..

I have three functions with different statements, and the tests show that they all return None

def w_pass():
    pass
def w_return():
    return
def w_return_none():
    return None

their contents are different, their results are the same because “all functions return None by default, as if they have an invisible line that says …”

I like to write my functions with explicit return statements, so that anyone can see what the function returns without having to think about it.


test_what_happens_after_functions_return

The return statement is the last thing to run in a function. No statements after it in a function will run when the function is called.


RED: make it fail


  • I go back to the terminal where the tests are running

  • I add a test to test_functions.py

    the terminal is my friend, and shows NameError

    NameError: name 'return_leaves_the_function'
               is not defined
    

    because Python does not know what I mean by return_leaves_the_function since I do not have a definition for it in this file, yet.


GREEN: make it pass


I change return_leaves_the_function to a variable by pointing it to None (the simplest object)

22def test_what_happens_after_functions_return():
23    # return_leaves_the_function
24    return_leaves_the_function = None
25
26
27# Exceptions seen

the test passes.


REFACTOR: make it better



test_constant_function

There are functions that always return the same thing when they are called. They are singleton or constant functions.


RED: make it fail


  • I go back to the terminal where the tests are running

  • I add a test

    the terminal is my friend, and shows NameError

    NameError: name 'constant' is not defined
    

    because Python does not know what I mean by constant since I do not have a definition for it in this file.


GREEN: make it pass


I change constant to a variable by pointing it to None

30def test_constant_function():
31    # constant
32    constant = None
33
34
35# Exceptions seen

the test passes.


REFACTOR: make it better


A constant function always returns the same thing when called, I can use them in place of variables. The number of cases where they are faster than variables is pretty small. It is something like if the function is called less than 10 times (who’s counting?)

All the functions I have written so far return the same value every time they are called.


close the project

  • I close test_functions.py

  • I click in the terminal where the tests are running

  • I use q on the keyboard to leave the tests. The terminal goes back to the command line.

  • I change directory to the parent of functions

    terminal
    cd ..
    

    the terminal shows

    .../pumping_python
    

    I am back in the pumping_python directory.


review

I ran tests to show that I can make functions with the def, pass and return keywords.

How many questions can you answer about functions?


code from the chapter

Do you want to see all the CODE I typed in this chapter?


what is next?

Would you like to make a person with strings?


rate pumping python

If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.