Functions

Functions in Python are reusable lines of code that only run once they are called on.

Functions can be used to shorten the overall lines of code needed in a program, as well as modify and return data.

The Syntax for functions is as follows:

def my_function():
    # Do stuff here .....
    return data # optional

Functions in Python follow similar naming conventions to that of variables, however we must include the def keyword before the function name and a set of parentheses after the function name.

Like loops and conditionals, the lines of code we want to run within a function must be indented correctly.

Calling Functions

If we wanted to execute, or call, the lines within a function, all we have to do is write the name of the function followed by parentheses. For example:

def say_hi():
    print("Hi!")
    # Notice no return statement

say_hi()

Function Parameters

Functions can also take input data that can be used within the function. These inputs are known as parameters and are defined when the function is defined. For example:

def introduce_person(first_name, last_name):
    print("Welcome " + first_name + " " + last_name + "!")

introduce_person("John", "Doe")

# Prints out "Welcome John Doe!"

In the example above, we have a function introduce_person that takes in two parameters, first_name and last_name, and prints out a string that greets that person.

Function parameters can be of any type and there can be an infinite amount of them defined within a function.

If a function is defined with a certain amount of parameters, then that function must be called with the same amount of arguments.

Function Returns

Python functions have an optional return statement, which allows functions to output data to variables. For instance:

def add(x, y):
    return x + y

summation = add(5, 4)

print(summation) # Prints 9

Closing Remarks

You may have noticed by now, but we have been using functions without even knowing it! The print function is a very useful built-in function in Python as it allows us to write notes/outputs directly into the console. Later on, we will see some more important built-in Python functions.