Functions and methods
Contents
Functions and methods¶
In Python we can also use functions (and a special kind of functions called methods) to build expressions. There are many many functions and methods, we present only some of them. The Python documentation lists some of the functions available in Built in functions.
Functions for integer numbers¶
The Python documentation lists functions specific for numbers in Numeric types
str(3)
'3'
abs(-3)
3
abs(3)
3
divmod(123456789,10)
(12345678, 9)
max(1,2)
2
max(5,4,3,2,1)
5
min(1,2)
1
min(5,4,3,2,1)
1
type(3)
int
Functions for floating point numbers¶
Many of the functions in Numeric types are for floating point numbers. There are many more in the library math
that you need to import if you want to use it. You import the library with the instruction
import math
(see the examples below).
import math
# pi is a number, not a function.
# Notice the use of the name of the library (math) and the .
math.pi
3.141592653589793
math.sqrt(2)
1.4142135623730951
# e is a number, not a function
math.e
2.718281828459045
math.log(math.e)
1.0
math.sin(math.pi / 2)
1.0
# almost 0!
math.cos(math.pi / 2)
6.123233995736766e-17
math.floor(3.1)
3
math.floor(3.6)
3
math.ceil(3.1)
4
math.ceil(3.6)
4
Functions and methods for strings¶
Methods are used in a strange way: expression.method(arguments)
! Instead of function(all the arguments)
. You should think of the expression to the left of the .
as being one more argument to the method.
In the examples below, len
is a function that has only one argument: the string for which it calculates the length. But split
is a method: it uses the string before the .
and results in a list of strings.
You can find very many functions and methods in Text sequence type.
len('this')
4
len('this is a sentence')
18
'this is a sentence'.split()
['this', 'is', 'a', 'sentence']
# You can specify the separator:
'this is a sentence'.split('a')
['this is ', ' sentence']
# Notice the empty string after the last 'e' in the result.
'this is a sentence'.split('e')
['this is a s', 'nt', 'nc', '']
# join uses the string before the dot as connector to put together all
# the strings in argument (a list of strings)
'_'.join(['this','is','a','sentence'])
'this_is_a_sentence'
# Notice the big T in the result!
'this is a sentence'.capitalize()
'This is a sentence'
'this is a sentence'.upper()
'THIS IS A SENTENCE'
'THIS IS A SENTENCE'.lower()
'this is a sentence'
'THIS IS A SENTENCE'.endswith('ENCE')
True
'THIS IS A SENTENCE'.startswith('THIS')
True
Functions for lists¶
Lots of functions and methods for lists are described in Sequence types.
len([])
0
min([1,2,3,4])
1
max([1,2,3,4])
4
sum([1,2,3,4])
10
sum([x ** 2 for x in [1,3,5,7,9]])
165
sorted([5,4,3,2,1])
[1, 2, 3, 4, 5]