Skip to content

Introduction to the function

What is it function?

Function is a group of instructions. We use it for several reasons:

  • If some part of code will be executed in many places, it's easier to create function and use it (call), than copy same part of code many times. It's important in case of failure, it needs to be fixed only in function body - one place instead of many. Sometime programs are large, without appropiate separation whole project/program management is time consuming. Smaller parts help to easier understand code.

Functions features:

  • Way to separated code into useful blocks.
  • Organize code.
  • Make it easier to read.
  • We can use functions which use same instructions instead of repeat same part of code.
  • It use input arguments.
  • Calculate and generate result based on input arguments.
  • They need to be defined before first time usage!

Function definition

Functions in Python are defined by using key word def, function name, optional arguments in brackets and function body with insctructions (need to remember about cut ins!).

    def function_name_1():
        <instructions>

    def function_name_2(arg_1, arg_2, ..., arg_n):
        <instructions>

Let's make some simple examples of function definitions:

    # Function definition with name print_hello_world
    def print_hello_world():
        print("Welcome in world from function inside!")
    # Function call print_hello_world()
    print_hello_world()

    # Function definition greet_by_name(name)
    def greet_by_name(name):
        print(f"Hi, {name}")
    # Function call greet_by_name(name) use value "John" as argument name
    greet_by_name("John")

Function print_hello_world not use any argument, but function greet_by_name read name argument and return it in other function: print.

Function naming convention

In Python, it is generally accepted that we write function names in snake case standard, it means next words are separated by '_'. Examples below:

  • good_function_name,
  • add_ingredients,
  • save_content_to_file.

All rules related to variable naming convention are applied in function.

Function parameters and arguments

Argument is a local function parameter. In general, parameters are used to declare a function and arguments to call function.

    def greet_by_name(name):
        print(f"Hi, {name}")

    greet_by_name("John")

Here is last example, name is parameter and "John" is an argument.

Function parameters can be:

  • obligatory,
  • optional (parameters named).

Arguments for obligatory parameters are used without their name. Argument for optional parameter are used with their name when function is called.

Functions can use any number of arguments, or none of them. Due to fact it's possible to use, not mean it required. In most cases lot of arguments are a sign of bad practice (eng. code smell). If method use many arguments, they are separated by commas.

Example of function call with arguments in positional and named way.

    # Function return name and surname
    def print_full_name(name, surname):
        print(f"{name} {surname}")

    # Function call without parameters
    print_full_name("Jon", "Snow")

    # Function call with all parameters names
    print_full_name(name="Jon", surname="Snow")

    # Function call with last parameter name
    print_full_name("Jon", surname="Snow")

In case when we don't provide parameter name due to function execution, arguments can be called in same order as in definition. Parameter name usage allows to change their order. Python will will know and assign to specific argument by name.

Default parameters

Default values can be assigned to function parameter when it defined. Those parameters don't need to be called during function call, but they can be changed to value ohter than default.

    # Function definition greet_by_name(name) with default name parameter value
    def greet_by_name(name="World!"):
        print(f"Hello, {name}")

    # Function call greet_by_name(name) without argument
    greet_by_name()  # Return "Hello, World!"

    # Function call greet_by_name(name) with "John" as name argument value
    greet_by_name("John") # Return 'Hello, John'

    greet_by_name(name="John") # Return 'Hello, John'

Functions - returned values

Functions in Python can return calculated values by using key word return. If word return is not used in function body, then function will return value None. Conclusion: function every time return something!

Example of Function return:

    def calculate_square(a):
        return a*a

    square = calculate_square(5)
    print(square)  # Return 25

Function body

Function body, it's whole code inside function right after function and parameters name. In previous example function body was code:

    return a*a

In this case function body contain only returned value, which was calculated base on provided argument. Usually function body have few to over a dozen lines. Remember that if more lines are in code it become more complex and difficult to maintain.

Functions with any number of arguments

Any number of positional arguments in function

Here is a function example, that calculate sum of next: two, three, four arguments:

    # Add two numbers
    def add(a, b):
        return a + b

    # Add three numbers
    def add(a, b, c):
        return a + b + c

    # Add four numbers
    def add(a, b, c, d):
        return a + b + c + d

What if user would like to add ten numbers? Will we need to create ten arguments function? What if we need to add 100 numbers?

Any number of function will help it.

  • Instead of large arguments number function, we can use *args parameter.
  • Arguments provided by user goes to list named args and will be available in function body.
  • It should be mentioned that name args is symbolic (we can change it to whatever else, that met naming convention), any number positional arguments are defined by using asterisk.

Some args usage in function examples:

    # Add any number of arguments
    def add(*args):
        result = 0
        for arg in args:
            result += arg
        return result

    print(add(1,2,3,4,5))  # Return 15

    # Return name and what else user provide
    def print_name_and_something(name, *strings):
        print(f"Name: {name}")
        for string in strings:
            print(string)

    print_name_and_something("Jack", "a", "b", "c", "d")

In add function definition only parameter is args. Asterisk before name means, that user can provide any number of arguments when function is called. Arguments will get into a list (in this case named args), and this list will be available in add function body.

Function print_name_and_something require minimum one argument (here: name). Argument name cannot be missed - otherwise Python will return error. All other positional arguments get to list named strings.

Function with any number of named arguments

There is a way to define function whit any number of named arguments.

  • Instead of many named arguments definition function we can use parameter **kwargs.
  • Named arguments provided by user will get into dictionary named kwargs and will be available in function body.
  • It should be mentioned that name args is symbolic (we can change it to whatever else, that met naming convention), any number named arguments are defined by using double asterisk before it name.

Some kwargs usage in function examples:

    # Add any number of arguments
    def add_ingredients(**kwargs):
        result = 0
        for key in kwargs:
            result += kwargs[key]
        return result

    print(add_ingredients(eggs=3, spam=5, cheese=2))  # Return 10

Function with any number of positional and named arguments

Any number of positional (*args) and named (**kwargs) arguments can be joined in one function signature.

    # Add any number of arguments
    def add_ingredients(*args, **kwargs):
        result = 0
        for arg in args:
            result += arg
        for key in kwargs:
            result += kwargs[key]
        return result

    print(add_ingredients(1, 2, 3, eggs=3, spam=5, cheese=2))  # Return 16