A function is a small chunk of reusable code that performs some task. Utilizing functions helps us easily debug and maintain our code. Functions also avoid code duplication and keeps our code looking clean. As a programmer, you should try to separate each small task within individual functions for better readability and good practice.
We've already looked at method and function calls earlier on. Let's now learn how to define our own functions.
To define a function, use the
def keyword (short for definition), followed by your function name. Within the following set of parentheses, specify your formal parameters.
The following function doubles a value and adds one to it.
def doubleAndAdd(n): return 2*n+1
Python requires that each line that is part of the function to be indented inward. If we don't indent each line within our function, then we get an error message.
def doubleAndAddOne(n): return n+1 File "<stdin>", line 2 return 2*n+1; ^ IndentationError: expected an indented block
return keyword is used to return a value to its caller. If no value is specified after the
return keyword, then
None is returned.
While developing programs, you may find yourself defining functions that are yet to be implemented. To avoid Python erroring out a function with no statements, use the keyword
pass as a filler until you figure out what to write.
def doubleAndAddOne(n): # TODO: implement doubleAndAddOne formula pass
As programmers, it's good practice to communicate to others about what our functions do. The opening line of the function is known as the docstring. It is a literal string value that describes the function. To declare it, use three double-quotation marks, right after the function definition.
def doubleAndAddOne(n): """This function returns an input value plus one.""" return 2*n+1
Now when the user prompts the help function, he or she can read the brief description.
>>> help(doubleAndAddOne) Help on function doubleAndAddOne in module __main__: doubleAndAddOne(n) This function returns an input value plus one. (END)
With every function execution, a new symbol table is created. The symbol table stores all the local variables that are initialized from within our function. Thus, when a variable is called, Python looks within the first symbol table on our stack. If nothing is found there, then it moves up to the next functions, then to the global symbol table and finally the built-in names. If still nothing is found, an error results.
The only way a global variable can be assigned is through the
Sometimes you want to make a function parameter value optional. In such cases, the parameters will take on a default value if the variable is undefined.
def doubleAndAddOne(n, double=False): """This function returns an input value plus one.""" return 2*n+1 if double else n+1 >>> doubleAndAddOne(2) # double is automatically set to False 3
To specify a variable, specify the variable and the value you want to give it.
>>> doubleAndAddOne(2, double=True) 5
You may want to specify an arbitrary number of arguments into variadic arguments. These will take in all other parameters and store it into a tuple. Precede this special argument with an asterisk (
def arb_arguments(*args, param = 'default'): print("arbitrary argument list:") for arg in args: print(arg) print("param = " + param) return
>>> arb_arguments(1,2,3,4) arbitrary argument list: 1 2 3 4 param = default >>> arb_arguments('hello', 'hi', 'whatsup', param = 'custom') arbitrary argument list: hello hi whatsup param = custom
Assertions can be used to check certain values from within a Python program. For example, we can write the following in our code to ensure we have a positive value.
def doubleAndAddOne(n): """ This function returns an input value plus one. """ assert n > 0 return 2*n+1
Now when we specify a negative value, we can see that our assertion fails.
>>> doubleAndAddOne(-2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, indoubleAndAddOne AssertionError
To create your own customer assertion error message, input a second parameter. This will be triggered if our assertion fails.
def doubleAndAddOne(n): """ This function returns an input value plus one. """ assert n > 0, "Please enter a positive value." return 2*n+1
Now we can see our own custom error message returned if a negative value is put in.
>>> help(doubleAndAddOne) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, indoubleAndAddOne AssertionError: Please enter a positive value.
To create an anonymous function, use the lambda keyword. In this function, we'll first assign
x, then let any future functions assign the other variables.
>>> def multiply(x): ... return lambda a, b: x * (a + b) >>> f = multiple(2) >>> f(3,4) # 2 * (3+4) 14
Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you learned.$ Check price
Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.$ Check price