DEV Community

Cover image for Introduction To Python Functions
Morris Mulitu
Morris Mulitu

Posted on

Introduction To Python Functions

What is a function in Python?

In Python, a functions are a group of related statements that do specific tasks.
Functions are used to create smaller chunks of code in python making programming more streamlined and organized. This hence makes code more understandable to others who who view it. Most importantly, functions make code less repetitive and enhance reusability.

def function_name(parameters):
    """docstring"""
    statement(s) 
Enter fullscreen mode Exit fullscreen mode

Using the example above;

  • The keyword def indicates the start of the function.
  • The function name is used to uniquely identify the function.
  • Parameters / arguments are used to pass values to the function. They however are optional.
  • The end of the function header is denoted by a colon(:)
  • The (docstring) segment used above details what the funtion is supposed to do.
  • There can be an optional return statement to return values from the functions.

Example

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")
Enter fullscreen mode Exit fullscreen mode

Calling a function in python

After defining a python function you can go on to call it from another function, a python prompt or maybe another program.
Type the function name and parameters to call it.

>>>greet('Morris')
Hello, Morris. Good morning!
Enter fullscreen mode Exit fullscreen mode

Complete function and its calling;

def greet(name):
    """
    This function greets to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")

greet('Morris')
Enter fullscreen mode Exit fullscreen mode

Output;

Hello, Morris. Good morning!
Enter fullscreen mode Exit fullscreen mode

Docstrings

The documentation string or docstring is the first string after the function header. It details what the specific function does. It is optional but hightly recommended. Use triple quotes to enable the docstrings to span over multiple lines.

Return statement

Used to exit the functions and go back to w herever it was called from.

return [expression_list]
Enter fullscreen mode Exit fullscreen mode

A return statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.

Example

>>> print(greet("May"))
Hello, May. Good morning!
None
Enter fullscreen mode Exit fullscreen mode

Here, None is the returned value since greet() directly prints the name and no return statement is used.

Example of return

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    if num >= 0:
        return num
    else:
        return -num


print(absolute_value(2))

print(absolute_value(-4))
Enter fullscreen mode Exit fullscreen mode

Output

2
4
Enter fullscreen mode Exit fullscreen mode

Python Function Arguments

You can define a function that takes variable number of arguments.

def greet(name, msg):
    """This function greets to
    the person with the provided message"""
    print("Hello", name + ', ' + msg)

greet("Monica", "Good morning!")
Enter fullscreen mode Exit fullscreen mode

Output

Hello Monica, Good morning!
Enter fullscreen mode Exit fullscreen mode

Here, the function greet() has two parameters.
If we call it with a different number of arguments, the interpreter will show an error message. Below is a call to this function with one and no arguments along with their respective error messages

>>> greet("Monica")    # only one argument
TypeError: greet() missing 1 required positional argument: 'msg'
Enter fullscreen mode Exit fullscreen mode
>>> greet()    # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'
Enter fullscreen mode Exit fullscreen mode

Variable Function Arguments

There are other ways to define a function that can take variable number of arguments.

Python Default Arguments
We can provide a default value to an argument by using the assignment operator (=).

def greet(name, msg="Good morning!"):
    """
    This function greets to
    the person with the
    provided message.

    If the message is not provided,
    it defaults to "Good
    morning!"
    """

    print("Hello", name + ', ' + msg)


greet("Kate")
greet("Bruce", "How do you do?")
Enter fullscreen mode Exit fullscreen mode

Output

Hello Kate, Good morning!
Hello Bruce, How do you do?
Enter fullscreen mode Exit fullscreen mode

In this function, the parameter name does not have a default value and is required (mandatory) during a call.

On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional during a call. If a value is provided, it will overwrite the default value.

Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.

This means to say, non-default arguments cannot follow default arguments. For example, if we had defined the function header above as:

def greet(msg = "Good morning!", name):
Enter fullscreen mode Exit fullscreen mode

We would get an error as:

SyntaxError: non-default argument follows default argument
Enter fullscreen mode Exit fullscreen mode

Python Keyword Arguments

When we call a function with some values, these values get assigned to the arguments according to their position.

For example, in the above function greet(), when we called it as greet("Bruce", "How do you do?"), the value "Bruce" gets assigned to the argument name and similarly "How do you do?" to msg.

Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result.

# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")

# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Bruce") 

1 positional, 1 keyword argument
greet("Bruce", msg = "How do you do?")  
Enter fullscreen mode Exit fullscreen mode

We can mix positional arguments with keyword arguments during a function call. But we must keep in mind that keyword arguments must follow positional arguments.

Having a positional argument after keyword arguments will result in errors. For example, the function call as follows:

greet(name="Bruce","How do you do?")
Enter fullscreen mode Exit fullscreen mode

Will result in an error:

SyntaxError: non-keyword arg after keyword arg
Enter fullscreen mode Exit fullscreen mode

Python Arbitrary Arguments

Sometimes, we do not know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with an arbitrary number of arguments.

In the function definition, we use an asterisk (*) before the parameter name to denote this kind of argument. Here is an example.

def greet(*names):
    """This function greets all
    the person in the names tuple."""

    # names is a tuple with arguments
    for name in names:
        print("Hello", name)


greet("Monica", "Luke", "Steve", "John")
Enter fullscreen mode Exit fullscreen mode

Output

Hello Monica
Hello Luke
Hello Steve
Hello John
Enter fullscreen mode Exit fullscreen mode

We have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all the arguments back.

Top comments (0)