What Is a Function?
A function is a block of code with a specific purpose to which you give a name. When you call that function, you execute the code it contains. Functions also let you input parameters to run the same code on different values.
There are different types of functions in Python:
Built-in functions provided with Python.
User-defined functions that programmers (that’s you!) create.
Define a Function
Think of a function as a way to reuse a repeatable set of instructions. You define it using the def
keyword, the name of the function, parentheses, and a colon :
. If the function requires one or more parameters, they go inside the parentheses separated by commas. Let’s say you want to add two numbers together. Below is a code snippet for an add()
method that takes in two numbers as the parameters and returns the sum.
def add(a, b):
return a + b
Now that you know what a function is, you can call it by placing values in for the parameters. These values are called arguments. The function will then return the values added together.
>> add(1,3)
4
>> add(403,123)
526
When you return a value in a function, you can also save it as its own variable when you call the function.
total = add(1,4)
What would total
be equal to, in this case?
If you guessed 5, you are correct! 😁 The add()
function lets you enter in any two numbers and get the sum in return.
When to Use Functions
When you write a lot of code, it’s easy to get lost and confused by all the different functionality you have going on. Functions help you break up your code into smaller sections, so you know what each part is supposed to do.
It ultimately results in you writing better, cleaner, and more readable code.
Level-Up: Use Functions
Let's put the fun in function! Practice using functions in this exercise. 😁
Then, check your work by:
submitting your project,
navigating back to the course team page (click on the exercise title on the top left of your screen, then the team name "OCpythonbasics")
clicking on "Fork the solution".
Let’s Recap!
Functions are ways to repeat functionality and separate code into different modules.
You can create functions with or without input parameters.
Functions are defined (written out code), called (execute the code), and can return information (send back a value).
In the next chapter, we’ll discuss how to write clean code and why it’s so important!