4.1.4 - Functions

Don't Repeat Yourself (DRY)

Functions are used for two reasons. First, they make code easier to read and understand. Second, they allow code to be used more than once. You’re already familiar with the print() and input() functions. Python provides several builtin functions like these, but you can also write your own functions. A function is like a mini-program within a program. To better understand how functions work, let’s create one. Type this program into Thonny script editor and save it as hello_func.

def hello(): print("Hi!") print("Hi!!!") print("Hello World.")

Press the run button and then at the CLI area write

>>> hello()
>>> hello()
>>> hello()

By defining a function we can make the program easier to read. To define a function, start by using the def command. After the def command goes the function name. In this case we are calling it hello. We use the same rules for function names that we use for variable names.

Following the function name will be a set of parentheses and a colon. All the commands for the function will be indented inside. The code in the block that follows the def statement is the body of the function. This code is executed when the function is called, not when the function is first defined.

The hello() is a function call. In code, a function call is just the function’s name followed by parentheses, possibly with some number of arguments in between the parentheses. When the program execution reaches these calls, it will jump to the top line in the function and begin executing the code there. When it reaches the end of the function, the execution returns to the line that called the function and continues moving through the code as before.

In general, you always want to avoid duplicating code, because if you ever decide to update the code—if, for example, you find a bug you need to fix—you’ll have to remember to change the code everywhere you copied it.

As you get more programming experience, you’ll often find yourself deduplicating code, which means getting rid of duplicated or copy-and-pasted code. Deduplication makes your programs shorter, easier to read, and easier to update.