Built-in classes and functions

The classes and functions shown on this page can be used without importing anything.

Input and output

input() str
input(prompt: str) str

Gets input from the user in the terminal window. This function waits until the user presses Enter. The input is returned as a string.

Parameters

prompt – If given, this is printed in the terminal window first. This can be used to ask a question so the user knows what to type.

Returns

Everything the user typed before pressing Enter.

print(*objects)
print(*objects, sep: str = "' '", end: str = "'\\n'", file: uio.FileIO = 'usys.stdin')

Prints text or other objects in the terminal window.

Parameters

args – One or more objects to print.

Keyword Arguments
  • sep – This is printed between objects, if there is more than one.

  • end – This is printed after the last object.

  • file – By default, the result is printed in the terminal window. This argument lets you print it to a file instead. This argument is not supported on the BOOST Move hub.

Basic types

class bool
class bool(x: Any)

Creates a boolean value, which is either True or False.

Parameters

x – Value that is tested for being True or False. It is converted using the standard truth testing procedure.

Returns

Result of the truth-test. If no object is given, it returns False.

class complex
class complex(string: str) None
class complex(a: Union[float, complex], b: Union[float, complex] = 0) None

Creates a complex number from a string or from a pair of numbers.

If a string is given, it must be of the form '1+2j'. If a pair of numbers is provided, the result is computed as: a + b * j.

Parameters
  • string – A string of the form '1+2j' .

  • a – A real-valued or complex number.

  • b – A real-valued or complex number.

Returns

Complex number, obtained from the string or as the result of a + b * j.

class dict(*args, **kwargs)

Creates a new dictionary.

class float
class float(x: Union[int, float, str]) None

Converts the argument to a floating point number. If no argument is given, this returns 0.0.

Parameters

x – Number or string that will be converted.

Returns

The input argument x converted to a floating point number.

class int
class int(x: Union[int, float, str]) None

Converts the argument to an integer. If no argument is given, this returns 0.

Parameters

x – Number or string that will be converted.

Returns

The input argument x converted to an integer.

to_bytes(length: int, byteorder: Literal[little, big]) bytes

Returns a bytes object representing the integer.

Parameters
  • length – How many bytes to use.

  • byteorder – Choose "little" for little-endian encoding or "big" for big-endian encoding.

Returns

The integer represented by a sequence of bytes.

classmethod from_bytes(bytes: Union[bytes, bytearray], byteorder: Literal[little, big]) int

Returns the integer represented by the given bytes.

Parameters
  • bytes – The bytes to convert.

  • byteorder – Determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte sequence. If byteorder is "little", the most significant byte is at the end of the byte sequence.

Returns

The integer represented by the bytes.

class object

Return a new featureless object.

class type(object: Any)

With one argument, returns the type of an object.

Sequences

class bytearray
class bytearray(source: int)
class bytearray(source: Union[bytes, bytearray, str, Iterable[int]])

Creates a new bytearray object, which is a sequence of integers in the range \(0 \leq x \leq 255\). This object is mutable, which means that you can change its contents after you create it.

  • If no argument is given, this creates an empty bytearray.

  • If the source argument is an integer, this creates a bytearray of zeros. The argument specifies how many zeros.

  • For all other valid source arguments, this creates a bytearray with the same byte sequence as the given source argument.

class bytes
class bytes(source: int)
class bytes(source: Union[bytes, bytearray, Iterable[int]])
class bytes(source: str, encoding: str)

Creates a new bytes object, which is a sequence of integers in the range \(0 \leq x \leq 255\). This object is immutable, which means that you cannot change its contents after you create it.

  • If no argument is given, this creates an empty bytes object.

  • If the source argument is an integer, this creates a bytes object of zeros. The argument specifies how many zeros.

  • If source is a bytearray, bytes object, or some other iterable of integers, this creates a bytes object with the same byte sequence as the source argument.

  • If source is a string, choose 'utf8' as the encoding argument. Then this creates a bytes object containing the encoded string.

len(s: Sequence) int

Returns the length (the number of items) of an object.

class list
class list(iterable: Iterable)

Creates a new list.

class slice(stop: int)
class slice(start: int, stop: int)
class slice(start: int, stop: int, step: int)

Returns a slice object representing the set of indices specified by range(start, stop, step).

Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i].

class str(object: Any = '')
class str(object: bytes = b'', encoding: str = 'utf-8', errors: str = 'strict')

Return a str version of object.

class tuple
class tuple(iterable: Iterable)

Rather than being a function, tuple is actually an immutable sequence type.

Iterators

all(iterable: Iterable) bool

Returns True if all elements of the iterable are true (or if the iterable is empty).

Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
any(iterable: Iterable) bool

Returns True if any element of the iterable is true. If the iterable is empty, returns False.

Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
class enumerate(iterable: Iterable)
class enumerate(iterable: Iterable, start: int)

Returns an enumerate object.

Equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
iter(object: Union[Iterable, Sequence]) Iterator

Returns an iterator object.

map(function: Callable, iterable: Iterable, *args: Any) Iterator

Returns an iterator that applies function to every item of iterable, yielding the results.

next(iterator: Iterator) Any
next(iterator: Iterator, default: Any) Any

Retrieves the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

class range(stop: int)
class range(start: int, stop: int)
class range(start: int, stop: int, step: int)

Rather than being a function, range is actually an immutable sequence type.

reversed(seq: Sequence) Iterator

Returns a reverse iterator.

sorted(iterable: Iterable, key=None, reverse=False) List

Returns a new sorted list from the items in iterable.

zip(*iterables: Iterable) Iterable[Tuple]

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted.

With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

Equivalent to:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

Conversion functions

bin(x: Any) str

Converts an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

chr(i: int) str

Returns the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a'.

This is the inverse of ord().

hex(x: int) str

Converts an integer number to a lowercase hexadecimal string prefixed with “0x”.

oct(x: int) str

Converts an integer number to an octal string prefixed with “0o”.

ord(c: str) int

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.

This is the inverse of chr().

repr(object: Any) str

Returns a string containing a printable representation of an object.

Math functions

See also umath for floating point math operations.

abs(x: Any) Any

Returns the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__().

divmod(a: int, b: int) Tuple[int, int]
divmod(a: float, b: float) Tuple[float, float]

Takes two (non complex) numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using integer division.

max(iterable: Iterable) Any
max(arg1: Any, arg2: Any, *args: Any) Any

Returns the largest item in an iterable or the largest of two or more arguments.

min(iterable: Iterable) Any
min(arg1: Any, arg2: Any, *args: Any) Any

Returns the smallest item in an iterable or the smallest of two or more arguments.

pow(base: int, exp: int) Union[int, float]
pow(base: int, exp: int, mod: int) Union[int, float]

Returns base to the power exp; if mod is present, returns base to the power exp, modulo mod.

The two-argument form pow(base, exp) is equivalent to using the power operator: base ** exp.

round(number: float) int
round(number: float, ndigits: int) float

Returns number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Tip

To print a number use a format function instead. Since many floating point numbers don’t have exact representations, round() often gives unexpected results!

Example:

# print two decimal places
print('my number: %.2f' % number)
print('my number: {:.2f}'.format(number))
sum(iterable: Iterable) int
sum(iterable: Iterable, start: int) int

Sums start and the items of an iterable from left to right and returns the total.

Runtime functions

eval(expression: str) Any
eval(expression: str, globals: dict) Any
eval(expression: str, globals: dict, locals: Mapping) Any

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The return value is the result of the evaluated expression. Syntax errors are reported as exceptions.

exec(object: Any) None
exec(object: Any, globals: dict) None
exec(object: Any, globals: dict, locals: Mapping) None

This function supports dynamic execution of Python code.

globals() Dict[str, Any]

Return a dictionary representing the current global symbol table.

hash(object: Any) int

Returns the hash value of the object (if it has one).

help() None
help(object: Any) None

Prints help for the object. If no argument is given, prints general help. If object is 'modules', prints available modules.

id() int

Returns the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime.

locals() dict

Updates and returns a dictionary representing the current local symbol table.

Class functions

callable(object: Any) bool

Returns True if the object argument appears callable, False if not.

dir() List[str]
dir(object: Any) List[str]

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

getattr(object: Any, name: str) Any
getattr(object: Any, name: str, default: Any) Any

Returns the value of the named attribute of object.

hasattr(object: Any, name: str) bool

The result is True if the string is the name of one of the object’s attributes, False if not.

isinstance(object: Any, classinfo: Union[type, Tuple[type]]) bool

Returns True if the object argument is an instance of the classinfo argument, or of a subclass thereof.

issubclass(cls: type, classinfo: Union[type, Tuple[type]]) bool

Returns True if cls is a subclass of classinfo.

setattr(object: Any, name: str, value: Any) None

Assigns the value to the attribute, provided the object allows it.

This is the counterpart of getattr().

super() type
super(type: type) type
super(type: type, object_or_type: Any) type

Returns am object that delegates method calls to a parent or sibling class of type.

Method decorators

@classmethod

Transforms a method into a class method.

@staticmethod

Transforms a method into a static method.