02. Functions

A function is a small chunk of reusable code that performs some task. Utilizing functions helps us easily debug and maintain our code. Functions also avoid code duplication and keeps our code looking clean. As a programmer, you should try to separate each small task within individual functions for better readability and good practice.

We've already looked at method and function calls earlier on. Let's now learn how to define our own functions.

Defining functions

To define a function, use the def keyword (short for definition), followed by your function name. Within the following set of parentheses, specify your formal parameters.

The following function doubles a value and adds one to it.

def doubleAndAdd(n):
  return 2*n+1

Python requires that each line that is part of the function to be indented inward. If we don't indent each line within our function, then we get an error message.

def doubleAndAddOne(n):
  return n+1
 
File "<stdin>", line 2
    return 2*n+1;
         ^
IndentationError: expected an indented block

Return

The return keyword is used to return a value to its caller. If no value is specified after the return keyword, then None is returned.

Doing nothing

While developing programs, you may find yourself defining functions that are yet to be implemented. To avoid Python erroring out a function with no statements, use the keyword pass as a filler until you figure out what to write.

def doubleAndAddOne(n):
  # TODO: implement doubleAndAddOne formula
  pass

Docstring

As programmers, it's good practice to communicate to others about what our functions do. The opening line of the function is known as the docstring. It is a literal string value that describes the function. To declare it, use three double-quotation marks, right after the function definition.

def doubleAndAddOne(n):
  """This function returns an input value plus one."""
  return 2*n+1

Now when the user prompts the help function, he or she can read the brief description.

>>> help(doubleAndAddOne)
Help on function doubleAndAddOne in module __main__:
 
doubleAndAddOne(n)
  This function returns an input value plus one.
(END)

Docstring Conventions

  • The first line should be a short, concise summary of object or function's purpose.
  • First line should start with a capital letter and end with a period.
  • We do not need to declare what type it is since the user can obtain that be other means.
  • If there are more than one line, then the second line should be blank.

Symbol table

With every function execution, a new symbol table is created. The symbol table stores all the local variables that are initialized from within our function. Thus, when a variable is called, Python looks within the first symbol table on our stack. If nothing is found there, then it moves up to the next functions, then to the global symbol table and finally the built-in names. If still nothing is found, an error results.

The only way a global variable can be assigned is through the global statement.

Default and optional parameters

Sometimes you want to make a function parameter value optional. In such cases, the parameters will take on a default value if the variable is undefined.

def doubleAndAddOne(n, double=False):
  """This function returns an input value plus one."""
  return 2*n+1 if double else n+1
>>> doubleAndAddOne(2)
# double is automatically set to False
3

To specify a variable, specify the variable and the value you want to give it.

>>> doubleAndAddOne(2, double=True)
5

Arbitrary arguments

You may want to specify an arbitrary number of arguments into variadic arguments. These will take in all other parameters and store it into a tuple. Precede this special argument with an asterisk (*).

def arb_arguments(*args, param = 'default'):
  print("arbitrary argument list:")
  for arg in args:
    print(arg)
  print("param = " + param)
  return
>>> arb_arguments(1,2,3,4)
arbitrary argument list:
1
2
3
4
param = default
>>> arb_arguments('hello', 'hi', 'whatsup', param = 'custom')
arbitrary argument list:
hello
hi
whatsup
param = custom

Assertions

Assertions can be used to check certain values from within a Python program. For example, we can write the following in our code to ensure we have a positive value.

def doubleAndAddOne(n):
  """ This function returns an input value plus one. """
  assert n > 0
  return 2*n+1

Now when we specify a negative value, we can see that our assertion fails.

>>> doubleAndAddOne(-2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, indoubleAndAddOne 
AssertionError

Custom assertion error messages

To create your own customer assertion error message, input a second parameter. This will be triggered if our assertion fails.

def doubleAndAddOne(n):
  """ This function returns an input value plus one. """
  assert n > 0, "Please enter a positive value."
  return 2*n+1

Now we can see our own custom error message returned if a negative value is put in.

>>> help(doubleAndAddOne)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, indoubleAndAddOne 
AssertionError: Please enter a positive value.

Lambda Expressions

To create an anonymous function, use the lambda keyword. In this function, we'll first assign x, then let any future functions assign the other variables.

>>> def multiply(x):
...    return lambda a, b: x * (a + b)
>>> f = multiple(2)
>>> f(3,4)        # 2 * (3+4)
14

Learn to be a Pythonista!

Introducing Python

Learn to be a Pythonista! Try Python

Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you learned.

$ Check price
39.9939.99Amazon 4.5 logo(37+ reviews)

More Python resources

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Ad