2016 September 16,

CS 111: Built-In Functions

Python offers many handy operations on lists. Here are a few:

new_list = [4, 6.2, 1, -9]

max(new_list)

min(new_list)

sum(new_list)

If you ask Python for the type of any of these operations — for example, type(max) — you'll learn that they are functions. A function is a piece of Python code that takes in some input, does some computation with it, and produces some output. For example, max takes one input, namely a list of numbers. It does some computation, namely finding the greatest number in the list. (How does it do this? I don't know, and I don't care. I don't need to know how the function works, to know what it does and to use it effectively.) Then it produces one output, namely that greatest number it found.

This function concept comes directly from mathematics. In fact, Python comes with a variety of math functions built-in. Here's how you access some of them:

import math

math.sqrt(2.0) / 2.0

math.sin(math.pi / 4.0)

math.log(100.0)

In the code above, the import math command loads the module called math module. A module, like a program, is simply a bunch of Python code. However, while a program is designed to accomplish a particular task, a module is more like a toolbox, consisting of various independent pieces of code, that can be used to help other programs. There are hundreds or maybe thousands of modules available for Python, written by various people around the world. Some come with the Python interpreter; others have to be downloaded and installed — which is sometimes easy and sometimes difficult.

Question 14A: What are the types of math.sin(0.0) and math.sin? What is the type of math itself?