Python Basics

Python Functions

Python functions

Python Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

def my_function():
    print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function():
    print("Hello from a function")

my_function()  # Hello from a function

Parameters

Information can be passed to functions as parameter:

def my_function(fname):
    print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Default Parameter Value

If we call the function without argument, it uses the default value:

def my_function(country = "Norway"):
    print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()  # Uses default value
my_function("Brazil")

Return Values

To let a function return a value, use the return statement:

def my_function(x):
    return 5 * x

print(my_function(3))  # 15
print(my_function(5))  # 25
print(my_function(9))  # 45