### Unit 5: Functions

The understanding of variable definitions and control statements is fundamental to any programming language. Furthermore, the syntax of basic data structures such as lists and strings is foundational to mastering the Python language. In this unit, we take another step to improve upon our program organization skills by introducing functions. When a given task is performed many times throughout a program, it is usually wrapped within a function so that it can be used or "called" whenever needed. This notion of creating a specific function or "procedure" to achieve a given task is part of a programming methodology known as "procedural programming". We will also briefly contrast this approach with the use of methods that are used in "object-oriented programming". We will discuss these in greater detail in Unit 10.

**Completing this unit should take you approximately 4 hours.**

Upon successful completion of this unit, you will be able to:

- analyze situations where using functions could improve a program;
- explain how functions are defined and how to use function syntax;
- use functions to better organize programs written in Units 2–4;
- apply functions and methods available from the Python
*math*library; and - apply functions and methods for generating and applying random numbers.

### 5.1: The Basics of Functions

- Functions are useful when we have a section of code that we need to use over and over again. Putting the section of code in the form of a function allows the reuse of code by calling the function. Functions are provided with input values, they then perform a computation using the input and, finally, return values as the function output. Python has many
functions such as__built-in__`print`

,`type`

, and`len`

(which you already have experience with). For example, in the case of the`len`

function, the input is a list and the output is the number of elements contained in the list. Methods are functions that can be used with objects. You have already used a number of methods associated with lists (such as append) and strings (such as find). We will learn about the creation of methods when we get to object oriented programming. But, it should be pointed out that the idea of using a method is similar to that of a function in the sense that methods have input values and return output values.

The beauty of a programming language is that, while the language has a finite number of commands, keywords and built-in functions, it is possible to create new

commands using functions and methods. As an example, assume you have a list of numerical data and you would like to find a value on that list. Assume further that you have a program that must perform this computation at many different points within the program. Under these circumstances it is sensible to write a function to solve this problem. Let's practice writing a function to find a value on a numerical list.*user-defined*#===================== #begin function definitions ... def findval(alist,x): #alist is the input list #x is the value being searched for #This function returns a bool True if found #and returns a bool False if not found for val in alist: if (val==x): return True return False #end function definitions #===================== #main code begins here ... a=[2,3,4,5,6,7,8] print(findval(a,4)) print(findval(a,29)) b=[45,34,78,89] print(findval(b,45)) print(findval(b,1470))

Copy, paste, and run this code in Repl.it to inspect and study its effect. There are many details to be discussed regarding the syntax of functions.-
The keyword
`def`

informs Python that a function is being declared - Notice the (:) and the indentation with rules similar to conditional statements and loops
__Function name__: The name of the function is`findval`

__Inputs__:`findval`

has two input variables,`alist`

and`x`

__Outputs__:`findval`

returns one output variable of type bool- The return keyword is responsible for returning the output value

Now that a new

has been created, the main code that follows can*user-defined function***call**the function as many times as needed and the function will respond to the specific input variables provided. By default, variables used within the function are**local**to the function and cannot be seen by the main commands that follow. The function cannot "see" the variables`a`

and`b`

. The main code that calls the function cannot "see" the variables`val`

,`alist`

, and`x`

within the function. By convention, functions are definedof a Python program. The main code that runs comes after all the functions have been defined.*at the beginning* -
The keyword
Read this for more on functions.

### 5.2: Some Useful Modules

Before delving into some Python libraries dealing with applied mathematics, visit this optional site to review trigonometry if you need a refresher.

Programming also involves simulating random experiments such as flipping coins or rolling dice. If you need to review these topics, visit this optional site for a refresher.

We have already seen using the import command for importing the matplotlib library and the numpy package. Much of Python's power rests in the vast collection of packages, libraries, and modules available for just about any application you could think of. The math module contains a host of mathematically oriented methods typical of what a programmer would need to perform basic calculations. Consider executing this set of instructions:

import math a=math.exp(1) print(a) b=math.pi print(b) x=100 print(math.log(x,10)) print(math.log10(x)) y=math.pi/2 print(math.cos(y)) print(math.sin(y)) y=8 z=1/3 print(math.pow(y,z))

Notice once again the object-oriented dot notation for calling a method. Just about any function that can be calculated on a sophisticated calculator can be performed using the math module. For the sake of simplifying the code, if you know exactly what methods are needed from a given library, you can select a subset using the

`from`

keyword. Consider the code from earlier rewritten using the`from`

keyword:from math import exp, pi, log, log10, cos, sin, pow a=exp(1) print(a) b=pi print(b) x=100 print(log(x,10)) print(log10(x)) y=pi/2 print(cos(y)) print(sin(y)) y=8 z=1/3 print(pow(y,z))

Now all the math method calls look exactly like function calls. Sometimes it is more convenient to use the reduced representation.

The ability to generate pseudo-random numbers is central to programming and simulation. The random module offers a set of methods for doing so. Try running this code:

import random as rn #set the seed to system clock time rn.seed() #test some methods in the random module a=rn.random() #uniform random number between 0 and 1 print(a) b=rn.uniform(7,20) #uniform random number between 7 and 20 print(b) c=rn.randint(100,200) #random integer between 100 and 200 print(c)

Observe that:

- For convenience, the as keyword along with the import command shortens the name of the module reference from
`random`

to`rn`

. - The "seed" of a random number generator defines the starting point. In actual applications, you want to set the seed to a random value (like the system clock time); otherwise, a pseudo-random list will always start with the same value and repeat itself.
- Three essential methods for generating random numbers are:

`random.random()`

- generate floating-point numbers between 0 and 1`random.uniform(a,b)`

- generate floating-point numbers between`a`

and`b`

`random.randint(a,b)`

- generate integers between`a`

and`b`

- For convenience, the as keyword along with the import command shortens the name of the module reference from

### 5.3: Application

While this example is not how we would perform encryption in practice, it is highly instructive for reviewing concepts covered so far regarding user-defined functions. Implement this example in Repl.it in order to solidify your working knowledge of Python.

### Unit 5 Review and Assessment

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 5. As you watch, work through the exercises to try them out yourself.

- Receive a grade
Take this assessment to see how well you understood this unit.

- This assessment
**does not count towards your grade**. It is just for practice! - You will see the correct answers when you submit your answers. Use this to help you study for the final exam!
- You can take this assessment as many times as you want, whenever you want.

- This assessment