# 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, which is then being unpacked into the result variables.
• We can also return a dictionary instead!

### 2.3 Anonymous (labmda) functions¶

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

## 3. Exercise¶

Write a function to test if x and y (the input) are relatively primes. Return True if x and y are relatively primes, False otherwise.

For example, 6 and 35 are relatively primes.

Notes: I made a mistake in the video. In the for loop, i should go from 2 to min(x, y). So, the range() function should be range(2, min(x, y) + 1.

The correct solution is shown below:

This lecture notes referenced materials from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.