Functions (very basics)

Functions (very basics)#

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Simple function definitions and calls#

Function blocks begin with the keyword def followed by the function name and parentheses (()).

  • The code block within every function starts with a colon (:) and is indented.

  • Any input parameters or arguments should be placed within these parentheses.

def print_hello():
    "hello printer"
    print("hello")


def myprint(my_var):
    "my hello printer"
    print("I print", my_var)


# function calls
print_hello()
print_hello()
myprint("First call of myprint")
myprint("Second call of myprint")
hello
hello
I print First call of myprint
I print Second call of myprint
  • The first statement of a function can be the documentation string of the function, also called “docstring”.

  • The statement return [expression] exits a function, optionally passing back an expression to the caller. No return statement or a return statement with no arguments is the same as return None.

Duck typing

In computer programming, duck typing is an application of the duck test—“If it walks like a duck and it quacks like a duck, then it must be a duck”—to determine whether an object can be used for a particular purpose

Duck typing on Wikipedia

def add(arg0, arg1):
    """Print and return the sum of the two arguments (duck typing)."""
    result = arg0 + arg1
    print("result = ", result)
    return result
add(2, 3)
result =  5
5
add("a", "b")
result =  ab
'ab'

Exercise 9

Write a function that returns the sum of the first argument with twice the second argument.

def add_second_twice(arg0, arg1):
    """Return the sum of the first argument with twice the second one.
    Arguments should be of type that support sum and product by
    an integer (e.g. numerical, string, list, ...)

    :param arg0: first argument
    :param arg1: second argument
    :return: arg0 + 2 * arg1
    """
    ...