Skip to main content

Functions

Functions are used to compartmentalize code into smaller chunks that you can reuse throughout your code.  Ideally, you would break your code into pieces with logical, repeatable steps.  For instance, you would not place your entire program into one function but you might place the code to write a file into a "writeFile" function.

# This is how a basic function is defined
# The terms 'filename' and 'data' are positional arguments which are passed into the functions local variable scope
# The second one shows how information can be returned from the function

def writeFile(filename, data):
  """Writes a file to disk"""
  f = open(filename, "w")
  f.write(data)
  f.close()
  
def readFile(filename):
  """Reads a file and returns it's data"""
  f = open(filename, "r")
  data = f.read()
  f.close()
  return data

 

Arguments passed into function can have default values.  These "optional" arguments must be placed after "required" arguments.

# Optional arguments are used like the example below
# All optional arguments should follow required arguments

def writeFile(filename, data, append=False):
  if append:
    f = open(filename, 'a')
  else:
    f = open(filename, 'w')
  
  f.write(data)
  f.close()
  
# Two ways to call this function
writeFile('test.txt', 'a line of text to write', append=True)  # This will append the text to the end of the file
writeFile('test.txt', 'a line of text to write')  # This will over write the entire file

 

 

If you have a ton of arguments or don't don't know how many until run time, consider this method.

# An example of *args where an unlimited number of positional arguments are passed to a function
# "args" is just a name it could be *integers the key here is the single "*" for positional arguments

def sum_numbers(*args):
  """Sums an unlimited list of arguments"""
  result = 0
  for x in args:
    result += x
  
  return result

# Called like this
value = sum_numbers(1, 2, 3, 4, 5, 6)

 

Key word based arguments can be passed to a function also.

# An example of **kwargs where an unlimited number of keyword arguments are passed to a function
# As with args kwargs is just a name and you can use whatever you need

def concatenate(**kwargs):
  """Joins any number of strings which are defined with key words"""
    result = ""
    for arg in kwargs.values():
        result += arg
    return result

# Called like this
value = concatenate(a="Some", b="String", c="Values")

 

Got a simple one-liner function? Consider using Lambda

# Some examples of using Lambda
# The key word 'Lambda' instructs the interpreter of the upcoming unnamed function
# The variables listed on the left of the ':' are the arguments
# The right hand side of the ':' is the function's action

# Add 10 to a number
x = Lambda a : a + 10
result = x(5)

# Sum two numbers
x = Lambda a, b : a + b
result = x(1, 2)


# Most commonly, a lambda is used within a function call.  For instance sort()
cars = [
  {'car': 'Ford', 'year': 2005},
  {'car': 'Mitsubishi', 'year': 2000},
  {'car': 'BMW', 'year': 2019},
  {'car': 'VW', 'year': 2011}
]

cars.sort(key=lambda x : x['year'])
# Now the cars list is sorted by year
# the x variable in the lambda expression references each item within the list
# the x['year'] references the year element of each item in the list