# Functions¶

Ha Khanh Nguyen (hknguyen)

## 1. What is a Function?¶

• Function here means user-defined function.
• If you anticipate needing to repeat the same or very similar code more than once, it may be worth writing a reusable function.
• Use def keyword to define a function.
• A function might have argument(s). Argument(s) is not required for a function.
• In my_function() above, x, y, and z are the arguments.
• z=1.5 means that if no value is provided for z, the default value of z is 1.5.
• Here is an example of a function with no argument:

## 2. Function Properties¶

### 2.1 Namespaces, scope, and local functions¶

• Functions can access variables in two different scopes: global and local.
• A variable scope in Python is also called a namespace.
• Any variables that are assigned within a function by default are assigned to the local namespace.
• The local namespace is created when the function is called and immediately populated by the function’s arguments.
• After the function is finished, the local namespace is destroyed (with a few exceptions).

### 2.2 Returning multiple values¶

• The function is actually just returning one object, namely a tuple.

### 2.3 Anonymous (lambda) functions¶

• Anonymous or lambda functions are ways of writing functions consisting of a single statement, the result of which is the return value.

## 3. Recursion¶

• Recursion, also known as recursive programming, is a method (function) exhibits recursive behavior when it can be defined by two properties:
• A simple base case (or cases) — a terminating scenario that does not use recursion to produce an answer
• A recursive step — a set of rules that reduces all successive cases toward the base case.

(modified from Wikipedia)

• The Fibonacci sequence is classic example of recursion:
• Fib(0) = 0 as base case 1
• Fib(1) = 1 as base case 2
• For all integers $n > 1$, Fib($n$) = Fib($n-1$) + Fib($n-2$)

### Exercise¶

Write a function named fib() that takes $n$ as an input argument, computes the $n$-th number in the Fibonacci sequence, and return it as the function output.

This lecture note is modified from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.