Chapter 7: Functions

Built-in functions

face Josiah Wang

Python provides many useful built-in functions. A complete list of built-in Python functions is available on the official documentation, although some of these are actually classes (e.g. range, int, str, float, enumerate). These will be prepended by the keyword class in the detailed documentation.

We have already seen a few of these functions, like len(), print(), isinstance(), id().

Python provides some built-in Mathematical functions:

>>> print(sum([2, 3]))
>>> print(min([4, 1, 7]))
>>> print(max([4, 1, 7]))
>>> print(abs(-4))           # absolute value
>>> print(pow(2, 4))         # 2 to the power of 4
>>> print(round(5.6))        # round to nearest integer 
>>> print(round(5.678, 2))   # round to nearest 2d.p.

You might also find any() and all() quite useful!

>>> all_true = all([True, True, True, True])
>>> print(all_true)
True
>>> all_true = all([True, False, True, True])
>>> print(all_true)
False
>>> any_true = any([True, False, True, True])
>>> print(any_true)
True

You can use the sorted() and reversed() functions to return a sorted/reversed sequence.

>>> numbers = [1, 5, 3, 7, 8, 2]
>>> sorted_numbers = sorted(numbers)
>>> print(sorted_numbers)
[1, 2, 3, 5, 7, 8]
>>> reversed_numbers = reversed(numbers)  # reversed returns an `iterator`.
>>> print(list(reversed_numbers))  # you will need to convert it to a list if you need a list
[2, 8, 7, 3, 5, 1]