Definition of a Function


A function is a block of code that only runs when it is called. A function is an abstraction and should perform a specific task. All functions consist of a header and a body.

  • The def keyword is used to define a function.
  • The name of the function should follow the same naming conventions as variables.
  • The parenthesis in the header is required.
  • The header always ends with a colon.
  • The first line of the body of a function should always include a docstring, which describes what the function does.
  • Parameters and return values are optional (see "Parameters & Arguments" and "Return Values" below).
  • Other names for function include: method, module, and subroutine.
Python Function Example


Parameters & Arguments


  • Parameter - A parameter is defined in the function header and acts as a local variable within the function. The variable won't be assigned a value until the function is called and a value is passed as an argument.
  • Argument - An argument is a value that is passed to a function when the function is called. The argument's value will be assigned to the parameter that's in the same position as the argument (i.e. 1st argument is assigned to 1st parameter, 2nd argument is assigned to 2nd parameter, etc.).
In [1]:
# Below is an example of parameters and arguments.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

def printCoordinate(x1, y1):     # x1 and y1 are parameters
    """Prints a formatted coordinate to the console."""
    
    print(f"({x1},{y1})")

    
a = 100
b = 101
printCoordinate(4, 2)            # 4 and 2 are arguments
printCoordinate(2, 3)            # 2 and 3 are arguments
printCoordinate(a, b)            # a and b are arguments
(4,2)
(2,3)
(100,101)


Return Values


You can specify what a function returns by using the return keyword, followed by the value you want to return. If you don't specify what a function returns, it will return "None" by default. It is important to note that a function will not execute any additional code within the function after you have returned from that function.

Return values can be very useful and can make a function much more flexible. For example, rather than forcing your function to print to the console, returning the value will allow you to "choose" where you want to print it when calling the function.

In [2]:
# Below is an example of returning something from a function.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

def square(number):
    """Returns the square of a number."""
    
    return number * number


print(square(2))
print(square(11))
numberToBeUsedLater = square(256)
result = f"The square of 23 is {square(23)}."
print(result)
    
4
121
The square of 23 is 529.


Variables & Scope


The scope of variable within a program is where that variable is visible. The scope, or availability, of a variable only exists within the region in which it has been created.

  • Local Scope - If a variable was created within a function or entity, then it is only visible and can be used within that function and it is said to be a local variable.
  • Global Scope - If a variable was created in the main program (not inside a function or entity), then that variable is said to be a global variable and is visible and can be accessed throughout the entire program.
In [3]:
# Below is an example of global vs local scope.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

globalVariable = 1

def someFunction():
    """Demonstrates variables and scope."""
    localVariable = 2
    
    print(f"Within function: globalVariable = {globalVariable}")
    print(f"Within function: localVariable = {localVariable}")


someFunction()
print(f"Outside function: globalVariable = {globalVariable}")
# print(f"Outside function: localVariable = {localVariable}")         # <== This would result in a traceback error.
Within function: globalVariable = 1
Within function: localVariable = 2
Outside function: globalVariable = 1

You can only access a global variable's value within a function. However, if you want to change it, you have to use a special keyword, called global.

In [4]:
# This example shows how a global variable's value outside a function won't change if you don't use the "global" keyword.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
globalVariable = 1

def someFunction1():
    """Demonstrates that you can't change the value of a global variable this way."""
    globalVariable = 2

someFunction1()
print(f"globalVariable = {globalVariable}")

# This example shows how a global variable's value outside a function will change if you use the "global" keyword.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def someFunction2():
    """Demonstrates how to gain access to changing the value of a global variable within a function."""
    global globalVariable
    
    globalVariable = 2

someFunction2()
print(f"globalVariable = {globalVariable}")
globalVariable = 1
globalVariable = 2


Default Parameters


While defining a function in Python, you can give parameters default values. There are referred to as default parameters. If a parameter has a default value and the caller doesn't provide an argument, then the parameter will use the default value instead. (Please note that if a parameter doesn't have a default value and the caller doesns't provide an argument while calling the function, then it will result in a traceback error.

In [5]:
# This example of parameters with default values.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

def mysteryGreeting(name="Samantha"):
    """Demonstrates the use of a default parameter."""
    print(f"Good afternoon {name}!")
    

mysteryGreeting("Johnny")
mysteryGreeting()
Good afternoon Johnny!
Good afternoon Samantha!

Notice in the second function call, when an argument wasn't passed to the function, the default value "Samantha" was used.


Keyword Arguments


When calling a function, if you know the name(s) of the parameter(s), you can use keyword arguments, instead of positional arguments, or a combination of the two. (Important Note: If you use keyword and positional arguments in the same call, the keyword arguments must be placed after all of the positional arguments.

In [6]:
# This example of using keyword arguments.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

def greeting(first, last):
    """Returns a greeting to the name sent as arguments."""
    print(f"Good afternoon {first} {last}!")
    
greeting("John", "Deer")                # Using Normal Positional Arguments
greeting(first="Suzie", last="Q")       # Using Keyword Arguments
greeting(last="Q", first="Suzie")       # Using Keyword Arguments (order doesn't matter)
greeting("John", last="Deer")           # Mixing Positional & Keyword Arguments
#greeting("Deer", first="John")         # Mixing Positional & Keyword Arguments (order does matter)
    
Good afternoon John Deer!
Good afternoon Suzie Q!
Good afternoon Suzie Q!
Good afternoon John Deer!


New Program Structure


Now that you know how to define functions, we will redefine a new program structure. This new structure will take advantage of the use of functions and allow you to modularize your programs and move around them at free will. This program structure is by no means the only way a program can be structured, but it is a good template to start with as a novice programmer.

In [7]:
# ====================================================================================================
# Program: 
# Author: 
# Description: 
# Date Modified: 
# Version: 

# ====================================================================================================
# Import Libraries

# ====================================================================================================
# Global Variables

# ====================================================================================================
# User-Defined Functions

# ====================================================================================================
# Main Function

# ====================================================================================================
# Call the Main Function