Chapter 3. Functions

In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name.

Function Calls

We have already seen one example of a function call:

>>> type(42)
<class 'int'>

The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this function, is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is also called the return value.

Python provides functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:

>>> int('32')
>>> int('Hello')
ValueError: invalid literal for int(): Hello

int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:

>>> int(3.99999)
>>> int(-2.3)

float converts integers and strings to floating-point numbers:

>>> float(32)
>>> float('3.14159')

Finally, str converts its argument to a string:

>>> str(32)
>>> str(3.14159)

Math Functions

Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions.

Before we can use the functions in a module, we have to import it with an import statement:

>>> import math

This statement ...

Get Think Python, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.