13. Built-in Functions¶
13.1 Numeric¶
x = '47'
y = int(x)
int
is a constructor for the typeint
.similarly, there is a
float
constructorabs
returns absolute value of a number. Works on floats and ints.divmod
returns both quotient and remainder in a tuple.complex
is a type constuctor for complex numbers. Example:y = x + 73j
ory = complex(x, 73)
Complete set of built-in functions are in the [documentation].(https://docs.python.org/3/library/functions.html)
13.2 String¶
s = 'Hello, World.'
print(repr(s))
prints the string itself.
repr
is a method that most classes have.
class bunny:
def __init__(self, n):
self._n = n
def __repr__(self):
return f'repr: the number of bunnies is {self._n}'
def __str__(self):
return f'str: the number of bunnies is {self._n}'
<>
x = bunny(47)
print(x) # defaults to the str version
print(repr(x)) # if there's no str method, it prints the repr method
13.3 Container¶
x = (1, 2, 3, 4, 5)
y = len(x)
returns lengthy = reversed(x)
provides an iterator with the reversed objecty = list(reversed(x))
provides a reversed listy = sum(x)
returns sumy = sum(x, 10)
returns sum(x) + 10min
,max
any
returnsTrue
if any of them areTrue
. Similarly,all
.z = zip(x, y)
returns an iterator.for a, b in zip(x, y):
enumerate
returns index and value.for i, a in enumerate(x):
13.4 Object¶
x = 42
y = type(x)
print(x)
print(y)
type
operates on an object and returns the class.to check in code,
y = isinstance(x, int)
y = id(x)
returns a unique number for an object. Same objects have the same id.