Many beginning programmers get overwhelmed by functions, and struggle to understand other people’s code or utilize functions in their own scripts. However, functions are a powerful programming feature and utilizing them will improve your code. To help you learn those skills, and start writing excellent functions right away, here are the six most important things to know about using Python functions.
Python Functions: 6 Key Things to Remember
- If they’re easy to write, they’re easy to read.
- Keep the syntax simple.
- Use the return command.
- Work with arguments.
- Separate the namespace.
- Document your functions.
1. Easier to Write, Easier to Read
Functions are useful for two reasons.
First, functions allow you to write a block of code once and use it multiple times. You only need to write and debug the code once. This saves you lots of time in the future. Functions also make your code easier to maintain because, if you need to update your function at some point, you only need to edit it in one place.
Secondly, writing functions can make your code easier for the reader to understand. If your function has a descriptive name (e.g. a function designed to calculate the tip on a restaurant bill could be called calculate_tip
) then anybody reading your code can understand what each line does without having to make sense of the calculations.
Pretend that I’ve written the previously mentioned calculate_tip
function and I want to calculate the tip for both myself and my friend. My friend’s bill is 21 dollars, mine is 32 dollars and we each want to leave a 20 percent tip. I can write the following code calling calculate_tip
twice to get the tip for each. Don’t worry about the syntax of the function for now, I’ll cover that in a second.
friends_bill = 21
my_bill = 32
tip_percent = 20
friends_tip = calculate_tip(friends_bill, tip_percent)
my_tip = calculate_tip(my_bill, tip_percent)
print(friends_tip)
print(my_tip)
The output of this code will be the amount that both my friend and I should leave for a tip. Notice how easy it is to read and understand that code. For both calculations we simply see a line stating that the tip amount is calculated based on the bill and the desired percentage, which is quite intuitive.
2. Basic Structure of Python Functions
All Python functions use the same basic structure. First you need to define the function, providing it a name and the arguments necessary for the function to process. Then you need to define the code that it will process each time you call it. And, finally, you need to specify the values to return (if any) when you call the function. Let’s use our calculate_tip
function example again:
def calculate_tip(bill, percent):
tip = bill * percent/100
return tip
The first line of code defines the function.
def
tells Python that the line is creating a new function.calculate_tip
is the name of the function, so Python now knows to use this code whenever you typecalculate_tip
.(bill, percent)
states that those two inputs are required whenever you call the function.- The
:
at the end tells the program to run the following indented code whenever you call this function.
The second line represents the calculations used by this function. Whenever somebody wants to calculate a tip this function multiplies the bill by the desired percentage and divides by 100 (converting the percentage to a decimal) to identify the intended tip amount.
Finally, the last line says the calculated tip is the output from the function, which can be passed to a variable as desired.
In the prior example of calculating our friend’s tip we used values of 21 dollars for the bill and 20 percent for the tip. The line calling calculate_tip
caused that code to run with bill = 21
and percent = 20
. Tip was calculated to be 21 * 20/100
, or 4.2
. The calculate_tip
function then returned 4.2
, which was stored to the variable friends_tip
. We then printed for easy viewing.
3. Returning Values
The previous section showed the basics of returning a value from a function. You use the return
command followed by a value to state what you want the output to be. One neat trick of Python functions is that you can return as many outputs as you like, so long as you assign them to enough variables.
For instance, we can make calculate_tip
more useful by having it also return the total bill with the tip included. Then the user can see both how much to leave for a tip and how much to pay in total. To do so we would modify calculate_tip
as follows.
def calculate_tip(bill, percent):
tip = bill * percent/100
total = bill tip
return tip, total
There are two additions to that code. First, we added a line between calculating and returning tip. That line adds the tip to the bill to find the total payment. The second change added total
to the return line, telling Python it should return both values whenever we call calculate_tip
.
We can store and read both outputs from these functions using slightly updated code as follows:
friends_tip, friends_total = calculate_tip(friends_bill, tip_percent)
my_tip, my_total = calculate_tip(my_bill, tip_percent)
print(friends_tip, friends_total)
print(my_tip, my_total)
Since calculate_tip
now returns two outputs, we needed to update the lines of code calling it to receive both outputs. To do so, both lines now have two variables. One stores the calculated tip, the other stores the calculated total. The same is true of the statements printing the outputs. Each line prints the tip, then prints the total.
4. Working With Arguments
The inputs required by a function are typically called arguments. They are sometimes called parameters, though arguments is the more common term.
There are a few tricks you can use when working with arguments.
First off, you can provide a default value for each argument directly in the function definition. If you know that you normally tip 20 percent you can enter that as a default value. Then you only need to specify the tip percentage if you want to use a number different than 20 percent. For instance, consider the following code:
def calculate_tip(bill, percent = 20):
tip = bill * percent/100
total = bill tip
return tip, total
friends_bill = 21
my_bill = 32
tip_percent = 10
friends_tip, friends_total = calculate_tip(friends_bill, tip_percent)
my_tip, my_total = calculate_tip(my_bill)
print(friends_tip, friends_total)
print(my_tip, my_total)
In the function definition you can see that tip_percent
is now set to 20
, indicating that 20 percent will be used if you don’t specify a value when calling the function. The line calling calculate_tip
to return my_tip
and my_total
only passes my_bill
as an input. Since the code doesn’t overwrite the default value of 20 percent, calculate_tip
uses 20 percent when performing the calculations.
On the other hand, the variable tip_percent
is set to 10 percent and used when calling calculate_tip
to identify friends_tip
and friends_total
. This overwrites the default 20 percent, and performs the calculations using 10 percent.
Python arguments can also be positional or keyword arguments, representing two different ways of specifying their values. Positional arguments are referenced based on their position in the function call, and keyword arguments are specified by referencing the name of the argument in the function call.
Let’s take a look at a few quick examples.
You’re already familiar with positional arguments, because that’s the form we’ve been using so far. To highlight how this works, consider the following code:
def calculate_tip(bill, percent = 20):
tip = bill * percent/100
total = bill tip
return tip, total
tip, total = calculate_tip(21, 15)
Notice how the function call doesn’t include any code specifying which number goes to which argument. Since that isn’t specified, these values are assigned to arguments based on their position. Since calculate_tip
looks for the bill variable first, it uses the first passed value (21
). The same is true for percent; since calculate_bill
expected percent to be second, it uses the second passed variable (15
).
We specify keyword arguments by referencing the specific keyword when passing in arguments. This allows you to specify the arguments in any order that you please. For instance, you could use the following code:
def calculate_tip(bill, percent = 20):
tip = bill * percent/100
total = bill tip
return tip, total
tip, total = calculate_tip(percent = 22, bill = 110)
In this example, the function call explicitly states that percent is to be 22
and bill is to be 110 dollars
. The fact that they’re in the opposite order from what calculate_tip
expects is fine because Python uses the keywords instead of the position.
5. Separate Namespace
In Python a namespace is a collection of variables and information about those variables. Different aspects of the program create new different namespaces, so you need to be careful about how you pass variables.
Functions are able to read values from the main external namespace, but they do not return to the external namespace unless explicitly stated.
This is important to remember for two reasons:
- You need to be careful when defining variables inside your functions. If you aren’t, you may end up using the same variable name as outside the function, and you may end up using the wrong value.
- You need to think carefully about the values that you want to return from the function. If you don’t return a variable as an output, it’s completely inaccessible to the external namespace.
Here’s an example highlighting those effects:
def calculate_tip(bill, percent = 20):
tip = bill * percent/100
total = bill tip
print(my_bill)
my_bill = 32
tip_percent = 10
calculate_tip(friends_bill, tip_percent)
print(total)
Notice a few specific things about this code. First, my_bill
is neither passed into or calculated in calculate_tip
. It only exists in the namespace external to calculate_tip
. Second, no values are returned from calculate_tip
, so the tip and total variables calculated within the function are within that namespace.
When we run that code we get the following output:
32
Traceback (most recent call last):
File “main.py”, line 18, in <module>
print(total)
NameError: name ‘total’ is not defined
You can see that calculate_tip
successfully printed my_bill
(32
) because it inherited that information from the external namespace. But the code errored out when printing total
because total
only exists in the namespace for calculate_tip
, and does not exist in the main namespace.
6. Documenting Your Functions
Documenting your code is extremely important. It’s your way of telling users how to use your code, and why you made the choices you did.
You may be thinking that documentation isn’t important in most of your code because you’re the only person who uses it. However, you’d be surprised at how quickly you’ll forget how your code works. If you ever write a function, then come back two years later, you’ll really appreciate the comments you left for yourself.
The bare minimum code documentation is to provide a little introduction at the start of your function. This documentation should introduce the purpose and methods of the function, then describe the needed inputs and outputs. The description is typically two or three sentences before one sentence descriptions of the inputs and outputs. Here’s an example for our calculate_tip
function:
def calculate_tip(bill, percent = 20):
'''
Calculates the tip and total for a given bill
and tip percentage. Processes for a single
bill at a time.
inputs
bill: Float. The price to be paid by the person.
percent: Float. The desired tip to be paid, expressed
as a percent of the bill.
outputs
tip: Float. The tip to be paid for the bill and tip percent.
total: Float. The total price to be paid, including the tip.
'''
tip = bill * percent/100
total = bill tip
return tip, total
Reading that documentation provides the key information a user needs to use the function correctly. Someone else can now understand the purpose of the function, the limitations, as well as the structure and purpose of the inputs and outputs.
You should document any assumptions you made, or highlight reasons why the code has to be the way you programmed it (which I didn’t do here because it was all pretty self-explanatory). These inclusions are a good way to communicate with others who may need to understand the calculation methods at a later date.
And that’s it! Now you know six of the most important tips for using Python functions.