Functions

Lesson Progress
0% Complete

A basic function definition in Python requires the following:

  • def – a function begins with the word def.
  • namedef is followed by the function’s name. The name, foo in this example, is chosen by the programmer to reflect what the function does.
  • parentheses – the name is followed by a pair of parentheses and a colon ():
  • body lines – code to run within the function is indented directly underneath the def.
def foo():
    x = 1
    y = 2

Return values

Functions can be called to return values which may be used as variables, within expressions, or to be fed into other functions. The return keyword ends a function and returns a value to the caller. If no value is given, the value None is returned.

def get_president():
    return 'Billy Kangaroo'

print(get_president())

The above example will print the string Billy Kangaroo. The print() function calls get_president() which returns the value Billy Kangaroo. This string is then used by the print() function to print to the console.

def get_president():
    return

print(get_president())

Removing the return value will print None as the function get_president() no longer returns the string. Additionally, removing the return and replacing it with some other code will create an implicit return with value None.

Parameters

External values may be passed to functions for use within them. These values may be provided as variables, literals or expressions in a comma-separated list within the function parentheses. See the following example.

>>> def square(num):
...     return num ** 2
>>> square(5)
25

The square() function is called with the value 5 given in parentheses. In def square(num), the keyword num points to the value given by the caller which can be used within the function. In the case of square(5), referencing num will retrieve 5. The square() function is therefore able to be used to square any given number.