Using Built-in Functions

A function is basically a complicated expression. It is a command that returns a value, but hides the details of how that value is determined. This is useful because we typically don't want to look at the details of how numbers are rounded or lists of numbers are sorted.

Python has a number of built-in functions for performing common tasks. For example, if we want to determine the absolute value of a number, we use abs().

In [1]:
abs(-2)
Out[1]:
2

A function call is composed of two parts, the name of the function and the arguments that the function requires to calculate the value it returns. In the example above abs() is the name of the function, and -2 is the argument.

Functions can take multiple arguments. For example, if we want to round pi to two decimal places we would use the round function with the arguments 3.14159 and 2, where the first argument is the number to be rounded and the second argument is the number of decimal points to round it to.

In [2]:
round(3.14159, 2)
Out[2]:
3.14

Python has lots of built-in functions including:

  • abs(): Absolute value
  • sum(): The sum of the numbers in a list
  • type(): Returns the type of a variable
  • max(): The maximum value from a list
  • min(): The minimum value from a list
  • str(): The string version of a variable
  • int(): The integer version of a variable
  • float(): The floating point version of a variable

A full list of Python's built-in functions is available at: http://docs.python.org/library/functions.html

Calling functions

When we call a function in a program we include it's name and the specific arguments that we want it to evaluate. The function can be used just as if we had typed in the value it returned.

In [3]:
abs(-1) + 2
Out[3]:
3
In [4]:
pi_approx = round(3.14159, 2)
pi_approx
Out[4]:
3.14
In [5]:
print(round(3.14159 + abs(-7), 3))
10.142