When programming, you will often encounter
calculations and logical operations you need to perform repeatedly. One way to handle this
is to write the same code over, and over, and over, and over, and -- ... -- over…
A better solution is to write a function. Functions enable you to reuse logic an infinite
number of times without repeating yourself. This is especially helpful to avoid moments
of deja vu. A better solution is to write a function. Functions enable you to reuse
logic an infinite number of times without repeating yourself. This is especially helpful
to avoid moments of deja vu… Time to begin… Before we write a function
of our own, call the directory function to see what objects are available to us... When you first start the Python interpreter,
you will see a list of 4 standard attributes. Once you define a function, it will appear
in the directory. To define a function, you write “d-e-f”
followed by the name of the function. We will call this function F. Next, you write parentheses.
Inside the parentheses you list the inputs to the function. Another name for “inputs”
is “arguments”. This function has zero arguments. Next, type a “colon” and press
return. The colon is how you start a new code block in Python. For our first function we will keep things
simple. We will pass. The word “pass” is how you tell Python to skip this line and
do nothing. Notice that we indented the code inside the function. In Python, you group
code by indentation. There. We have created our first function.
It is short. It is simple. But does it work? To call the function, type the name and parentheses…
The function F did nothing, just like we told it to. By the way, look what happens if you forget
to type parentheses. Without parentheses, Python displays that
F is a function, and gives the memory address. Interesting, but not very helpful. You need
to include parentheses to actually call the function. If you call the directory function again,
you will see that F is now listed. Now we will write a function that actually
does something. We start with d-e-f. We will name this function
ping. Next, list the arguments inside parentheses. This function will have zero arguments. Finally,
type colon and press enter. Functions in Python can return values. To
return a value, type the word “return” and then the object. This function will return
the string “Ping”. To show our enthusiasm, we will type an exclamation point. Return
values are optional; you are under no obligation to return something. Now call the function. This function returns the string ‘Ping’.
Since we did not assign this to a variable, Python printed it to the terminal. But we
can also store the return value to a variable. To see that this worked, print the value X. Call the directory function again and you
will see the function Ping, and the variable X listed.
For our next example, recall the the volume of a sphere is:
V = 4/3 π r3, where R is the radius of the sphere. We will write a function which will return
the volume of a sphere when given the radius. To do this, we will need to use the number
Pi. This is available in Python, but first you must import the math module. If you display
the directory of the math module, you will see Pi listed. You can now access the number pi. We are ready to define the volume function.
Type ‘def’ then the name of the function. We will call this function ‘volume’. This
function will have a single argument: the radius R… Next, we will write a brief comment
describing this function. This is called a “docstring” and provides documentation
on what the function does and how to use it. Next, we compute the volume.
Notice that we used decimals for the fraction 4/3. This is because in Python 2, if you divide
one integer by another, it returns the quotient, not the exact value. Also, notice that you
use a double asterisk for exponents. Finally, return the volume. Let’s test this function. Compute the volume
of a sphere with radius 2. It works… Because we used an argument when defining
the function, you must provide an input when calling it -- R is a required argument. Look
what happens if you call ‘volume’ without an argument -- you get an error and a reminder
to use an argument. We can use the help function to see how to
use the volume function… Very helpful… We have created functions with no arguments
and with one argument. We will now throw caution into the vacuum of space and write a function
with two arguments. Our function will compute the area of a triangle. Recall that the area
of a triangle is ½ base x height. Our previous function was named “volume”,
which was somewhat vague. The name does not tell you what shape is being considered. This
time, we will be more explicit and name the function “triangle area”. To compute the
area, we need two arguments: the base B and the height H. Write a docstring giving a brief
description of this function… And finally, return the area of the triangle. We are ready to test the function. The area
of a triangle with base 3 and height 6 is … 9. This is correct. There is no limit to how many arguments you
can use in your function, but if the number of inputs is too large, you will alienate
others and receive accusing glares... Functions in Python can accept another kind
of argument called “keyword arguments”. To show how to use these kinds of arguments,
we will write a function which converts a person’s height from American Units (feet and inches) to centimeters. Recall that 1 inch equals 2.54 cm, and 1 foot
equals 12 inches. Call this function cm, for centimeter.
This function will accept two arguments: feet and inches.
Notice that these arguments have equal signs after them.
It looks as if we are assigning values to these arguments.
In fact, we are. We are assigning a default value of 0 to each argument. For this reason,
Python also calls keyword arguments “default arguments”... Next, write a docstring describing
the function. Notice that it is customary to use triple-quotes for a docstring.
Now for the actual code. We first convert inches to centimeters… Then we convert feet to centimeters… And we return the combined value. We could have combined these all on one line,
but it is better to write clean code which is easy to read, as opposed to compact code
which impresses no one. Here is how you call a function with keyword
arguments. First we convert 5 feet to centimeters… Next we convert 70 inches to centimeters… And lastly, convert 5 feet 8 inches to centimeters… We can also perform this last calculation
by specifying inches first… Keyword arguments help you to write flexible
functions and clean code. There are 2 kinds of arguments you can use
when writing a function. A keyword argument, which has an equal sign, and a required argument
which does not have an equal sign. When writing a function, you can use both kinds of arguments.
But if you do this, the keyword arguments must come last. For example, if you define a function G with
a keyword argument first, you get a Syntax Error. Notice that Python calls these “default
arguments”. This is another name for a keyword argument. To fix this, you have to list the non-default
arguments first. These are also called required arguments since they are required. To call this function, you must pass in a
value for the required argument Y. The keyword argument X is optional. If you do not provide
a value for X, the default value is used. If you want to pass in a value for the keyword
argument, then you must specify it by its name. Required arguments are not given a name.
They are determined by their position. Functions in Python are flexible contraptions.
Required arguments, keyword arguments, docstrings, return values -- together they empower you
to write some amazing, reusable code. And if your function does not require an input,
you will not get an argument from me...