How do we define a function in Python?
How can we call a function in Python?
In Python (and many other languages), it is possible to assign a name to list of instructions and run them all using just that name. We call this named list of instructions a function. For example, we have a program with duplicate instructions:
a = 1234 + 5678
b = a * a
c = b - a
print "The first result is:", c
a = 9 + 13
b = a * a
c = b - a
print "The second result is:", c
Notice that we're calling the same operations multiple times with different values. This is a case where using functions will help improve our code, so let's rewrite it:
def doThings(input1, input2):
a = input1 + input2
b = a * a
r = b - a
return r
c = doThings(1234, 5678)
print "The first result is:", c
c = doThings(9, 13)
print "The second result is:", c
Let's break this example down. We defined a function named "doThings" using the following line. The instructions that are part of the function are indented below it.
The variables input1 and input2 are called parameters.
def doThings(input1, input2):
We called our function with the following line. Just like the math functions, our Python function takes some input and produces an output value. Our inputs are 9 and 13, and we store our output in the variable named "c".
c = doThings(9, 13)
We end our function with the return keyword. This lets Python know which value we want to return from the function. In this case, it's returning the value of the variable named "r".
return r
Writing functions in Python has a close analogy to the plotting functions we saw in the previous lesson. Consider, again, the function f(x) = 2x + 3. Here the name of the function is f, the single parameter is x, and what is returned is 2x + 3. If we would like to see this in Python it would look like:
def f(x):
return 2*x + 3
y = f(10)
print "f(10) is: ", y
How would you define a function that doubles a number?
How about a function that prints its input?