Functions


15 min.   |   Advanced  

Defining a Function

Use the def keyword to define a function.

Parameters and Arguments

You can pass data into functions using parameters.

Return Values

Use return to send a result back to the caller.

Default Parameter Values

You can give parameters default values.

Keyword Arguments

You can pass arguments by name, in any order.

Variable Number of Arguments

Use *args for any number of positional arguments.

Use **kwargs for any number of keyword arguments.

Functions Returning Multiple Values

You can return more than one value using tuples.

Functions: Exercises

Tip Functions: Exercise 1

The absolute error between a true value y and prediction \hat{y} is

\lvert y - \hat{y} \rvert

Compute the absolute error for each pair of values in the abs_error() function and return the error list.

Tip Functions: Exercise 2

In Data Science, we often normalize a list of values so they sum to 1:

p_i = \frac{x_i}{\sum_j x_j}.

Normalize the numbers using the normalize() function and return the probs list.

Tip Functions: Exercise 3

A Bernoulli random variable takes values 1 (success) or 0 (failure). Its probability mass function is

P(X = x) = \begin{cases} p & \text{if } x = 1, \\ 1-p & \text{if } x = 0. \end{cases}

Compute the probability of each outcome if p = 0.3 using the bernoulli() function and return the probs list.

Tip Functions: Exercise 4

The Fibonacci sequence is defined by

F_1 = 1,\quad F_2 = 1,\quad F_{n} = F_{n-1} + F_{n-2}.

Use the function fib() to generate the first 8 Fibonacci numbers and return the sequence list.

Tip Functions: Exercise 5

Consider the polynomial represented by f(x)

f(x) = x^3 + 2x^2 + 5x + 10.

Compute the polynomial function f() for each value in the list below and return the list ys.