def print_hello_world():
print("Hello, world, from my function!")4.0 Getting to Know Functions
For more information on Functions, always read the Python documentation on functions.
Functions are the building blocks of programming. They create reusable operations that can be invoked simply by calling their name. This functionality is a huge time saver. It allows us to write code once and use it multiple times without duplication. Moreover, we can save functions separately and import them in our code. For this reason, any set of operations that might be needed more than one time should be turned into a function.
In many ways functions are like mini-programs within our larger program. They can take inputs (parameters), perform operations, and return outputs. Functions can also be used to organize code into logical sections, making it easier to read and maintain. This chapter will describe the many ways to create and use functions.
The Basics
We have been using functions throughout this textbook so far. Functions are characterized by their parentheses (). Whenever we have used (or called) something in python that had parentheses follow it, we were using a function. For instance, print() and random(), which we have seen in previous chapters were both functions, which was denoted by the parentheses. If we want to create a function of our own, we only need to define it with the keyword def, give it a name, add parentheses, and then a colon. The content of the function is then indented to form a code block. Remember indentation is important in Python, as it indicates the scope of the code block. Keep everything you want on the same block of code in the same indentation level. Here is a simple example of a function that prints “Hello, world!”:
Now that we have defined a function, that does not mean it runs. In fact, the code inside the function will not run unless we tell it to. All we have to do is invoke the function. Invoking the function is when we call its name with the parentheses.
print_hello_world() Hello, world, from my function!
If we call the function without the parentheses, it will do nothing. Because this text is being produced in a Jupyter Notebook runtime, it will print how Python evaluates the uninstantiated function.
print_hello_world<function __main__.print_hello_world()>
Return Values
Functions can also return values. This means that they can produce an output that can be used later in the program. To return a value from a function, we use the return keyword followed by the value we want to return. For instance, we can create a function that adds two numbers and returns the result:
def add_numbers():
return 5 + 10The return keyword also acts as and end to the function. Anything that comes after the return statement will not be executed. So if we add a print statement after the return, it will not run. Most IDEs will also indicate that the code after the return statement is unreachable, which is a good indication that we should not have it there. You can see below
def add_numbers():
return 5 + 10
print("This will not be printed.")Storing Function Return Values
The neat thing about a function’s return value is that we can store it in a variable as well. For instance, we can store the result of the add_numbers() function in a variable called result:
result = add_numbers()
print(result)15
Blocked Scope
Variables declared in Functions have their scope blocked. Blocked scoping means that variables declared within the function block only exist within that block. Their variables will not be used outside the scope. For instance, if I declare a variable x in a python script, it will be available globally. It has what we call global scope. I can call on it anywhere. Functions, however, have local scope. They cannot call variables declared outside of them, unless it accepts it as a parameter (see the next section).
x = 10
def new_function():
x = 12
print(f"local x = {x}")
new_function()
print(f"global x = {x}")local x = 12
global x = 10
Notice, that after new_function() is called and declares x to equal 12, it does not actually redefine the global variable x. Instead, it creates a new local variable x that only exists within the function. This is why the global x remains unchanged when we print it outside the function.