This lesson covers the following topics:
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.
# 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
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.
# 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)
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.
# 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.
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.
# 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}")
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.
# 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()
Notice in the second function call, when an argument wasn't passed to the function, the default value "Samantha" was used.
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.
# 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)
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.
# ====================================================================================================
# Program:
# Author:
# Description:
# Date Modified:
# Version:
# ====================================================================================================
# Import Libraries
# ====================================================================================================
# Global Variables
# ====================================================================================================
# User-Defined Functions
# ====================================================================================================
# Main Function
# ====================================================================================================
# Call the Main Function