You've learned how to use a couple of built-in functions in the previous course. Today you'll start learning how to create your own functions. But you might be wondering why have functions at all?
When your code consists of small amounts of commands and calculations, you may omit functions completely (neither use existing nor create your own). But if you're writing a more serious program, you will definitely require functions. They help to organize your code and to make it easier for other programmers to read. Functions are blocks of code that make programs more manageable and structured.
On a conceptual level, functions are like machines. Functions must be built (defined) beforehand. Building a function is a very strict, rigid process. We must follow a specific pattern to create a valid function definition. It must start with the header —
def keyword followed by a special fragment of code. Then follows the body — one or more lines of code that perform the actual work, whatever you want the function to do. The body is the main part of the definition.
People often refer to different aspects of functions, but use the same word “function”. Sometimes, they mean “function definition”, sometimes “function call” or "body. It might be confusing at first, but it usually makes sense from context. In our courses we try to be as explicit as possible and call things with their full names.
Recall that in the
pow call, we couldn't observe the process of exponentiation. We could only guess by seeing the result. So, what was happening inside the
pow function? To understand that, we're going to create our own function that mimics
pow. You already know how to use
pow, but today you will understand how it works inside. In programming, like in many hands-on practical fields, the best way to learn how something works is to create it from scratch.