O

Functions

Functions are one of the cornerstones of programming. They provide a way to reuse code. If you’ve ever copy-pasted lines of code just to change a few parameters, then turning those lines of code into a function not only makes your code more readable but also prevents you from making mistakes later on. Every time code is copy-pasted, it adds another place to look if a correction is needed, and puts that burden on the programmer. When you use a function, you need to make a correction only once, and it will be applied every time the function is called.

I highly suggest the Software-Carpentry Python episode on functions for more details.1 An empty function looks like this:

1. https://swcarpentry.github.io/python-novice-inflammation/08-func/index.html

def empty_function():
  pass

The function begins with the def keyword, then the function name (i.e., how the function will be called and used), a set of round brackets, and a colon. The body of the function is indented (one tab or four spaces). This indentation is extremely important. If you omit it, you will get an error. In this example, pass is used as a placeholder to do nothing.

Typically functions will have what’s called a “docstring”—a multiple-line comment that describes the function’s purpose, parameters, and output, and that sometimes contains testing code. When you look up help documentation about a function in Python, the information contained in the function docstring is usually what shows up. This allows the function’s documentation and code to travel together, which makes the documentation easier to maintain.

def empty_function():
  """This is an empty function with a docstring.
  These docstrings are used to help document the function.
  They can be created by using 3 single quotes or 3 double quotes.
  The PEP-8 style guide says to use double quotes.
  """
  pass # this function still does nothing

Functions need not have parameters to be called.

def print_value():
  """Just prints the value 3
  """
  print(3)
# call our print_value function
print_value()
3

Functions can take parameters as well. We can modify our print_value() function so that it prints whatever value we pass into the function.

def print_value(value):
  """Prints the value passed into the parameter 'value'
  """
  print(value)
print_value(3)
3
print_value("Hello!")
Hello!

Functions can take multiple values as well.

def person(fname, lname):
  """A function that takes 3 values, and prints them
  """
  print(fname)
  print(lname)
person('Daniel', 'Chen')
Daniel
Chen

The examples thus far have simply created functions that printed values. What makes functions powerful is their ability to take inputs and return an output, not just print values to the screen. To accomplish this, we can use the return statement.

def my_mean_2(x, y):
  """A function that returns the mean of 2 values
  """
  mean_value = (x + y) / 2
  return mean_value

m = my_mean_2(0, 10)
print(m)
5.0

O.1 Default Parameters

Functions can also have default values. In fact, many of the functions found in various libraries have default values. These defaults allow users to type less because users now have to specify just a minimal amount of information for the function, but also give users the flexibility to make changes to the function’s behavior if desired. Default values are also useful if you have your own functions and want to add more features without breaking your existing code.

def my_mean_3(x, y, z=20):
  """A function with a parameter z that has a default value
  """
  # you can also directly return values without having to create
  # an intermediate variable
  return (x + y + z) / 3

Here we need to specify only x and y.

print(my_mean_3(10, 15))
15.0

We can also specify z if we want to override its default value.

print(my_mean_3(0, 50, 100))
50.0

O.2 Arbitrary Parameters

Sometimes function documentation includes the terms *args and **kwargs. These stand for “arguments” and “keyword arguments”, respectively. They allow the function author to capture an arbitrary number of arguments into the function. They may also provide a means for the user to pass arguments into another function that is called within the current function.

O.2.1 *args

Let’s write a more generic mean() function that can take an arbitrary number of values.

def my_mean(*args):
  """Calculate the mean for an arbitrary number of values
  """
  # add up all the values
  sum = 0
  for i in args:
      sum += i
  return sum / len(args)
print(my_mean(0, 10))
5.0
print(my_mean(0, 50, 100))
50.0
print(my_mean(3, 10, 25, 2))
10.0

O.2.2 **kwargs

**kwargs is similar to *args, but instead of acting like an arbitrary list of values, they are used like a dictionary—that is, they specify arbitrary pairs of key–value stores.

def greetings(welcome_word, **kwargs):
  """Prints out a greeting to a person,
  where the person's fname and lname are provided by the kwargs
  """
  print(welcome_word)
  print(kwargs.get('fname'))
  print(kwargs.get('lname'))
greetings('Hello!', fname='Daniel', lname='Chen')
Hello!
Daniel
Chen
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.248.162