Understanding functions is crucial when learning to program.
Different people need different explanations for functions to really "click". So we'll try different approaches.
In short: a function is a bundle of functionality that you can use to accomplish some task.
Here are some different definitions. They are all correct, but one may make more sense to you:
Here are some examples:
lenfunction lets you count the letters in a string
minfunction lets you find the smaller of two numbers
maxfunction lets you find the larger of two numbers
absfunction calculates the absolute value of a number, turning a negative number positive
openfunction opens a file for reading or writing
You can also write your own functions.
If you've never heard of functions before, you can think of a function as a machine that you put something into. The machine does some work, and out comes a result.
You may also know about functions from mathematics. For example, in math we might write f(x) = x+2.
Here, f is an example of a function.
The inputs to a function call are called arguments.
The inputs to a function definition are called parameters.
When a function is called, the parameters take the values that you supplied as arguments.
The output of a function is called its return value.
See the Python function syntax page.
min. These are called "built-in functions".
This means that they were written by the creators of Python for you to
conveniently use in any Python program. You can see a list of all Python's built-in
Other programming languages have different built-in functions.
Knowing about these functions gives you access to useful functionality, so
they are worth remembering. Even if you don't remember precisely what
was called, now you know it exists, and you can always google, say, "how to
find the length of a string in python" to find out again.
You can also create your own functions that you can call anytime you want.
One of the main reasons to create your own functions is that it lets you group lines of code. If you need to run the group of code multiple times, you can simply call the function several times instead of copy-pasting the code. This is clearer and more maintainable.
Once you've written the functions you need, you can quickly piece them together to accomplish a lot in no time.
Functions are one of the most important building blocks to master when learning to program.
When an experienced programmer solves a problem, they will usually break the problem down into a series of small steps to be solved. For each step they will write a function solving that step. Finally they will call each function in turn to solve the full problem.
This is an extremely effective way to solve problems, because each function must accomplish only a single, small task. That's how almost all large programs are constructed.