IntroductionCode would quickly become an ugly and unruly mess if there wasn't a way to easily repeat and reuse it. You've already seen some of that with loops. They're great for repeating the same task multiple times right away. What if you wanted to reuse a block of code whenever you wanted? Well, that's where functions come in.
Here's another trip back to math class. If you remember, functions took in a number, did something to it, then outputted the new value. They were often represented in tables with the input on one side and the output on the other. Functions in programming are similar. Sometimes they take input. Sometimes they don't. Much of the time they return a value as well, but they don't always have to. In every case, they are used to repeat an operation whenever they are used, and that's the greatest similarity with the math concept.
Actually, you've already been using functions through much of this guide. Every time you've put a string or a list in
pop()on a list, you were using a function. Yes, they were called methods then, but methods are just a special type of function used in object oriented programming. There's no need to get too far into that now, though. All you need to remember is that functions aren't hard or scary, and they make the lives of programmers a whole lot easier.
Creating FunctionsCreating functions is a lot like creating loops. Python uses the colon and indentation to denote the beginning of a code block, and functions are no different. Instead of using a loop keyword to begin the block, though; functions use
def print_hello(): print("Hello World!")The structure of a function is like a cross between a loop and a variable. You start off with a keyword,
defthen assign it a name. Function names are exactly like variable names. They should be lower case with words separated by underscores. While you would name a variable by what it is, you name a function by what it does. In that way, variables are like nouns, and functions are like verbs.
If you tried to run that, you noticed something pretty odd. Nothing happened. Functions are building blocks that you store for later. When you create them, they aren't automatically used. Creating a function simply opens up the possibility to use it later.
Calling FunctionsUsing a function is called calling it. You always call a function by its name. So, take a look at the function from before and call it to see exactly what it does.
def print_hello(): print("Hello World!") print_hello()Now, you can see that it prints out
Hello World!. With functions, you can use them as many times as you'd like and include them in the regular flow of code.
def print_hello(): print("Hello World!") print_hello() new_list = [[2, 4, 6], [3, 6, 9], [4, 8, 12]] for list in new_list: for x in list: print(x) print_hello()Because functions are meant to be reusable, they can be used repeatedly with ease. Given that this function only contains one line, it's not a great example of the time and space that they save, but imagine if the function contained ten or more lines of code. It'd be terrible to have to write all of that every time it needed to be used, and it would make your code more prone to mistakes.
Passing Data To FunctionsUsing functions without giving them anything to work with only utilizes a fraction of their true capabilities. Functions are designed to take in data, manipulate it, and return it in a changed form.
Remember in the past when you gave methods information by adding it to the parenthesis? Well, that's how you pass data to a function. So, take a look at how this works.
def square(x): return x ** 2 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers: print(square(number))There's a lot going on there. First, in the definition of the function,
xis placed in the parenthesis. This is called a parameter. Parameters are function specific variables. Notice how
xis being used in the function without being explicitly defined elsewhere.
Then, there is the keyword
return. It specifies what the function should give out when it's done. Because of that, it also immediately ends the function. The next bit might seem somewhat abstract. The value of the function itself is the same as what the
returnstatement is. So, in the example,
print()returns the value of of
x ** 2when given
square(number)because the value of
square(number)is equal to its
There is one more major thing going on there. Look at the function call. It is being passed
number. This is referred to as a function argument. Arguments are given to functions when they are called and take the place of the function parameters when they are run.
Functions can have multiple parameters and take multiple arguments. The order of the parameters corresponds directly to the order of the arguments. Make sure they match.
def multiply_numbers(x, y): return x * y print(multiply_numbers(5, 4))It really is that simple. Just separate both the parameters and the arguments with a comma.
One final point should be made about
return. It isn't strictly needed. If you want a function that takes in information and saves it to a variable or something along those lines, it doesn't need to return anything.