# Python Functions

Last Updated | Jan, 05, 2021 By Kingsley Ijomah
In this article, you will learn all about functions, what a function is and the syntax of a function, we will also look at function arguments and all the different types in Python, we will learn about the recursive functions with an example. This is a perfect article for a beginner to Python.

## What are Functions?

A function in Python is an organised reusable block of code that is used to perform a single action. We can create functions of our own e.g a function that adds two numbers together or we can use python's built-in function such as `print()`

Below is the syntax of a Python function:

code
``````def function_name(parameters):
"""docstring"""
statement(s)``````

## Creating and Calling a Function

code
``````'''
we define a function called greet which accepts
a parameter called `name`
'''

def greet(name):
"""This function greets a person passed in as an arguement"""
return "Hello {}, Good Morning!".format(name)

'''
here we call the greet function with an argument `Adam`
'''

Above we have written our first function called `greet`, it has a parameter called `name`, whenever we call this function we have to supply it with a name, directly below the function is a `docstring` with tripe quotes, this is a way of documenting our function to make it understandable.

Finally, our greet function returns a value, not all functions return a value, to return a value we use the `return` statement.

When we create a function e.g `def greet(name)` we say greet has a parameter called `name` and when we call the function e.g `greet("Adam")` we say we called it with an argument `Adam`

Parameter when you define the function and argument when you call the function.

Below we are going to have a look at different types of arguements.

## Arguments

Above we have already seen examples of calling Python function with arguements, let's see another example but this time of calling the same function with multiple different arguements.

code
``````'''
Calling the same function with different arguments
changes the result of the function in the example below.
'''

def greet(name):
"""This function says greets a person passed in as a parameter"""
return "Hello {}, Good Morning!".format(name)

print(greet("Kingsley")) # output: Hello Kingsley, Good Morning!
print(greet("Dayana")) # output: Hello Dayana, Good Morning!
print(greet("Pamela")) # output: Hello Pamela, Good Morning!``````

## Arbitrary Arguments

If you are not sure how many arguments will be passed into your function, then you can add `*` before the parameter name in the function, this causes the function to receive a tuple of arguments, that can be accessed based on indexing.

code
``````'''
Example function with  arbitrary arguments
'''

def fruits(*names):
"""This function displays the fruit names"""

# names are tuple with arguments
for fruit in names:
print(fruit)

# output: Orange Banana Apple Grapes
fruits("Orange", "Banana", "Apple", "Grapes")``````

In the example above, `*names` parameter will return a `tuple` object and there for calling `for in` loop will print out all supplied fruits argument.

It is also possible to access the arguments using index position as shown below:

code
``````'''
Access the argument in the first position.
'''

def fruits(*names):
"""This function displays the fruit names"""

# names are tuple with arguments
print(names[0])

# output: Orange
fruits("Orange", "Banana", "Apple", "Grapes")``````

## Keyword Arguments

You can also have arguments in Python with the key = value pair syntax, this way the order of the arguments does not matter, let's explore this below with an example:

code
``````'''
The first example without keyword args, 'Daniel' has to come first
'''

def greet(name, msg):
"""This function greets to the person with the provided message"""
return "Hello {}, {}".format(name, msg)

# output: Hello Daniel, Good morning!
print(greet("Daniel", "Good morning!"))

# output: Hello Good morning!, Daniel
print(greet("Good morning!", "Daniel"))

'''
Now let's see how this can be avoided with the keyword argument
as shown below:
'''

# output: Hello Daniel, Good morning!
print(greet(name="Daniel", msg="Good morning!"))

# output: Hello Daniel, Good morning!
print(greet(msg="Good morning!", name="Daniel"))``````

As you an see from the above, using keywords when calling the functions makes it possible not to care about the positioning of the arguments.

## Arbitrary Keyword Arguments

If you are not sure how many keyword arguments will be passed into your function, then you can add `**` before the parameter name in the function, this causes the function to receive a dictionary of arguments.

code
``````def person(**student):
return "Hello {} {}!".format(student["fname"], student["lname"])

# output: Hello Kingsley Ijomah!
print(person(fname="Kingsley", lname="Ijomah"))``````

As you can see from above, have the parameter `**student` meant we could access it as a dictionary `student["fname"]` and` student["lname"]` etc.

## Default Parameter Value

It is also possible to write a function with default values, so when we call the function without any arguments it will use the default values. Check out the example below:

code
``````'''
Example with default value provided to name parameter
'''
def greet(name="David"):
"""This function says greets a person passed in as a parameter"""
return "Hello {}, Good Morning!".format(name)

# output: Hello David, Good Morning!
print(greet())``````

When the above is executed, as you can see, `greet()` is called without passing in any argument, yet it prints out `Hello David, Good Morning`, that is done using the default, when you provide a value, that value will override the default.

## The pass Statement

It is not possible to create an empty function, if you do then it will raise `unexpected EOF error`, so if for some reason you want to have an empty function, maybe as a reminder of required function you need to write, then you need to use the `pass` statement as show below.

code
``````'''
Running this will produce an error:
SyntaxError: unexpected EOF while parsing
'''
def greet(name):

'''
Using the pass statement will not raise an error
'''
def greet(name):
pass``````

## Recursion

In Python, a function can call other function, but it is also possible for a function to call itself. When a function calls itself this is known as a recursive function.

Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 5 is `5*4*3*2*1 = 120`.

code
``````def factorial_recursive(n):
if n == 1:
return True
else:
return n * factorial_recursive(n - 1)

# output: 120
print(factorial_recursive(5))``````

Above is the power of recursion, first we start with when to terminate the recursion, once n equals 1 we return True which terminates the recursive function.

The else statement is where the recursive function takes place, you notice we call factorial_recursive inside factorial_recursive with `n * (n - 1)` so in each recursion it will decrease from` 5 * (5-1)` to `2 * (2 -1)` when it gets to 1 just before the else becomes `1 * ( 1 - 1 )` then it is terminated.

## Built-in functions

Until now we have written our own functions, there are also Python built-in functions, some of which we have used such as `print() len() int()` below is a list of built-in functions in Python:

code
``````'''
abs()        delattr()     hash()      memoryview()   set()

all()        dict()        help()      min()          setattr()

any()        dir()         hex()       next()         slice()

ascii()      divmod()      id()        object()       sorted()

bin()        enumerate()   input()     oct()          staticmethod()

bool()       eval()        int()       open()         str()

exec()       isinstance()  ord()       sum()          bytearray()

filter()     issubclass()  pow()       super()        bytes()

float()      iter()        print()     tuple()        callable()

format()     len()         property()  type()         chr()

frozenset()  list()        range()     vars()         classmethod()

getattr()    locals()      repr()      zip()          compile()

globals()    map()         reversed()  __import__()  complex()

hasattr()    max()         round()    breakpoint()
'''``````

For more details on each function read more on Python's documentation: https://docs.python.org/3/library/functions.html

## Final Thoughts

Well done on reading to the very end of this post, now you know all you need to write functions, you learnt about parameters and arguments, and also you learnt about all the different types of arguments, arbitrary arguments, keyword arguments.

We also learnt about recursion and lastly a long list of all built-in function of Python 3, as time goes on and you keep practicing your Python programming you will find yourself using more and more of these functions.

Happy coding!...

If you like this post, please share it so others could benefit from it too.

# MY STORY

My name is Kingsley Ijomah, I am the founder of CODEHANCE, an online education platform built with you in mind, a place where I express my gratitude to a skill ( coding ) which has changed my life completely.