Python Functions

Functions are reusable blocks of code that can be executed more than once in a program. You can access a function by its name. There are many built-in functions in Python like print(), len(), str(). You can define your own function using def keyword followed by the name of your function.

def my_function():
    """ A simple function that only prints a text to console."""
    print("> My function is executed")

Function Arguments

Sometimes functions need some arguments to work properly. For instance, consider you are coding a function that adds two numbers and prints the result. For this scenario, your function definition should take two arguments.

def print_sum(num1, num2):
    """ This function adds two numbers. """
    print("Sum of two numbers is: " + str(num1 + num2))

print_sum(3, 5)
# Output:
# Sum of two numbers is: 8

Arguments with Default Values

You can assign a default value to an argument. In the following example, the argument greeting_word has a default value “Hello”. If you provide a value for greeting_word argument when calling greet() function, provided value will be used instead of the default value.

def greet(name, greeting_word = "Hello"):
    print(greeting_word + " " + name)

greet("John")        # prints "Hello John"
greet("John", "Hi")  # prints "Hi John"

Returning Values

Sometimes you might need functions that return a value. For instance, if you need to calculate the area of a circle you can write a function to keep your logic modular and reusable.

import math

def area_of_circle(r):
    """ This function returns area of a circle """
    a = r**2 * math.pi
    return a

area = area_of_circle(1)
print("Area of a circle with radius 1 is: " + str(area))
# Area of a circle with radius 1 is: 3.14159...

Keyword Arguments

Normally, you give arguments to a function in the same order as function definition. For print_employee_info function, first argument is name, second argument is surname and third argument is id.

However, you can change the order if you specify the argument name as name-value pairs.

def print_employee_info(name, surname, id):
    print("EmployeeInfo -> Name: " + name +
          ", Surname: " + surname + ", Id: " + str(id))

print_employee_info("George", "Miller", 5)
print_employee_info(surname = "Miller", id = 5, name = "George")

Arbitrary Number of Arguments

Some functions can take arbitrary number of arguments. These arguments are also called varargs (variable number of arguments). Syntax for a vararg is (*arg).

minimum function in the following example can take any number of arguments. The function iterates all arguments in a loop and returns the minimum value.

def minimum(*numbers):
    min_number = numbers[0]
    for number in numbers:
        if number < min_number:
            min_number = number
    return min_number