Introduction to Programming Week 3
Contents
Summary
Part 1: What is a Function?
A function in Python is a block of code that performs a task. In programming terminology, functions aren't used, they're called. If necessary, functions can take input in the form of parameters, and return output.
Functions are used to simplify coding, by allowing different parts of a program to share code (they could both call the same function), and by abstracting away implementation details (for example, you can use Python's built-in square root function without needing to know how it's implemented).
The general syntax for a function call is
result = function(parameter1, parameter2)
A function might have any number of parameters, which are given in parentheses after the function name and separated by commas. However, in general, functions will have at most one output, which in the code above would be stored in the variable result.
We've already seen a couple examples of functions, including the print function and input function.
Part 2: More Functions
The abs function returns the absolute value of a number, while len returns the length of a string or sequence, and round(x,n) rounds the float x to n decimal places. The max function returns the "largest" of its inputs. For numbers the behavior is as you would expect, while for strings it returns the string that would come latest in a dictionary.
Functions can be combined in complex expressions, with the output of one or more functions serving as input to others.
Part 3: Modules
Not all of the many functions built into Python are loaded by default - we usually only need a few of them, so that would be very inefficient. Instead, Python organizes functions into modules, which we can load as needed. Modules are loaded with an import statement:
import moduleName
While import statements can technically be anywhere, programmers usually put them at the beginning of their programs, so the entire program can use them.
To use a function from a module, we need to preface the function name by the module name and a period. So, for example, if we wanted to use the randint function in the random module we'd have to type something like
import random # this should be at the beginning of the program x = random.randint(1,10) # assigns to x a random integer between 1 and 10 (inclusive)
Any python file can also be imported as a module. For example, suppose we defined a function myFunc in myProg.py. Then in any other program (saved in the same directory) we could use myFunc by typing
import myProg #note that we omit the .py myProg.myFunc()
Note that when importing a program Python runs the program, so in the above example myProg would be run when it's imported (if there is anything to run, that is). It's possible you'd want to import a module without running the code it contains, but how to do so is beyond the scope of this class.
Part 4: Our Own Functions
Of course, there's more to programming than using the functions built in to Python. We can also define our own functions with the reserved word def, followed by the name we chose for the function, and the names of any parameters in parentheses, separated by commas. Finally, the last character of that line should be : (a colon), to signal to Python that the body of the function follows.
Python uses indentation to distinguish between different blocks of code, so after the first def line every line of the function should be indented. The semi-official standard is four spaces, although you could technically use any amount so long as you're consistent.
The first line in the body of any function should always be a special type of comment called a docstring, which should describe what the function does. Docstrings are delimited by three quotation marks, either double quotes ("""this is a docstring""") or single quotes ('''this is also a docstring'''). Docstrings are what Python looks for when you use the help function, so if you call help on your function Python will return the docstring for that functions.
Finally, the indented lines after the docstring make up the body of the function. Functions can have any number of lines, the end of a function is defined by the end of the indentation.
Functions that will produce output need a return statement. The expression following the word return will be the output of the function. Functions can only return once, so as soon as the return statement is executed the function stops. Hence, return statements are usually the last line of a function.
For example, the following is a very simple function, that returns a number five more than its input:
def addFive(x): """Adds five to the parameter""" return x+5
Note that variables created within a function are local to that function. They're destroyed when the function exits, and can't be referenced by other parts of the program.
Internally Python treats functions as any other type of data, so one unusual feature of Python is that functions can be assigned to variables, and passed as parameters to other functions.