9. Functions

In this lesson you will learn how to create functions and call them.

Why Use Functions?

Functions are a great way to limit the number of lines you have in your code. Functions are first defined with a name and then contain code. When you call the function, the code under the function runs. Functions are useful since like variables, if you are repeating the same segment of code multiple times, you can use a function and then call the function every time you use the code. Another reason to use functions is it helps others use your code without needing to know how it the code underneath works. For example, the print statement is a function and although we do not know how to program our own print statement we can use the function and it does all the work for us.

Functions Without Arguments

To create a function we first need to define it with a name using the keyword def. Make sure to have parentheses and a colon. Just like loops and conditionals, the code underneath or inside of the function needs to be indented. To then call a function, call the name of the function with parentheses following it. Here is an example of a simple function:

def hello():
    print("Hello there!")

hello()

Functions With Arguments

One of the uses of functions is when we pass in a parameter. A parameters is the variable that is listed inside of the parentheses when defining a function and an argument is the value that is sent or passed to the function when it is called. To create a parameter, add the variable name of the parameter inside of the parentheses when defining a function. Then to call the argument inside of the function, use the parameter name defined in the function definition. Here is an example of a greeting function that takes in a string for the name:

def greet(name):
    print("Hello " + name)

greet("Andrew") # Hello Andrew
greet("Bob")    # Hello Bob
greet("Billy")  # Hello Billy

Note how when passing the argument, we just put the string inside of the function when we called it.

If we wanted multiple arguments, we can just add more variables inside of the parentheses in the function definition and separate them with commas. Then when we call the function we once again separate the variables with commas or do "parameter_name=value". Below is an example of both:

def greet(name1, name2):
    print("Hello " + name1 + " and " + name2)

greet("Andrew", "Bob")             # Hello Andrew and Bob
greet(name2="Andrew", name1="Bob") # Hello Bob and Andrew

Note how when you set the parameter with an equal sign you can set the parameters in any order you want.

But what if we had an unknown number of arguments that is going to be passed into the function? To do this we will need to utilize the asterisk. Then to call each argument inside of the function, reference the arguments with square brackets. Here is an example:

def print_third_number(*nums):
    print(nums[2])

print_third_number(1, 2, 3, 4, 5) # 3

If you try to call a function without passing an argument, you will receive an error. To get around this you have to set a default value to a parameter. To do this simply set the parameter equal to a value when you define the function. Below is an example:

def say(a="hi"):
    print(a)

say() # hi

Another powerful ability functions have is returning a value. To return a value simply type return followed by what you want to return. Here is an example of an adding function:

def add(a, b):
    return a + b

print(add(1, 3)) # 4

Note how you can put functions inside of other functions.

Scope

A variable created is only available from inside the region it is created. There are two types of variables, local and global. Local variables can only be used inside of the local scope it was created whereas global variables can be used be within local and global scopes. Global variables are defined inside of the main body of the Python code and local variables are defined inside of a function and can only be accessed from inside of the function. Below are some examples of using local and global variables:

def a():
    a = 3 # local variable
    print(a)
a() # 3

x = 100
def b():
    print(x) # prints the global variable x
b() # 100

def c():
    x = 50 # local variable, not a global variable
    print(x)
c()      # 50
print(x) # 100

If you want to create a global variable from within the local scope you can use the global keyword. You can also use the global variable to change the value of a global variable. Here are some examples:

def a():
    global x # this is a global variable
    x = 100
    print(x)
a()      # 100
print(x) # 100

def b():
    global x
    x = 10 # changing the global variable within a local scope
    print(x)
b()      # 10
print(x) # 10
❮ PreviousNext ❯