What is x n in Python 1


19.8 Built-in functions

In the course of the book there has been talk of built-in functions. These are predefined functions that are available to the programmer at any time. For example, you already know the built-in functions and. All of the built-in functions relevant to date are described in detail below. Note that there are other built-in functions that cannot be discussed here because they require concepts from object-oriented programming. A complete overview of all functions built into Python can be found in the appendix to this book (Section A.2).

Built-in function description section
Calculates the amount of the number. 19.8.1
Checks whether all elements of the iterable object result in the value. 19.8.2
Checks whether at least one element of the iterable object yields the value. 19.8.3
Generates a printable string that describes the object. Special characters are masked so that the output only contains ASCII characters. 19.8.4
Returns a string that represents the integer as a binary number. 19.8.5
Generates a Boolean value. 19.8.6
Creates a new instance. 19.8.7
Creates a new instance. 19.8.8
Returns the character with the Unicode code point. 19.8.9
Creates a complex number. 19.8.10
Generates a dictionary. 19.8.11
Returns a tuple with the result of an integer division and the remainder.
is equivalent to
19.8.12
Returns an enumeration iterator for the passed iterable object. 19.8.13
Evaluates the Python expression. 19.8.14
Executes a Python code. 19.8.15
Allows you to filter out certain elements of an iterable object. 19.8.16
Generates a floating point number. 19.8.17
Formats a value with the format specification. 19.8.18
Creates an immutable set. 19.8.19
Returns a dictionary with all references of the global namespace. 19.8.20
Returns the hash value of the instance. 19.8.21
Starts Python's built-in interactive help. 19.8.22
Returns the hexadecimal value of the integer in the form of a string. 19.8.23
Returns the identity of the instance. 19.8.24
Reads a string from the keyboard. 19.8.25
Generates an integer. 19.8.26
Returns the length of an instance. 19.8.27
Generates a list. 19.8.28
Returns a dictionary containing all references of the local namespace. 19.8.29
Applies the function to each element of the passed iterable objects. 19.8.30

Returns the largest element of. 19.8.31

Returns the smallest element of. 19.8.32
Returns the octal value of the integer in the form of a string. 19.8.33
Creates a file object. 6.4.1
Returns the Unicode code of the character. 19.8.34
Performs a power operation. 19.8.35
Outputs the transferred objects on the screen or in other output streams. 19.8.36
Generates an iterator over a sequence of numbers from to. 19.8.37
Returns a string representation of the instance. 19.8.38
Creates an iterator that traverses the iterable object backwards. 19.8.39
Rounds the number to decimal places. 19.8.40
Generates a lot. 19.8.41
Sorts the iterable object. 19.8.42
Generates a string. 19.8.43
Returns the sum of all elements of the iterable object. 19.8.44
Creates a tuple. 19.8.45
Returns the data type of an instance. 19.8.46
Combines several sequences into tuples, for example to run through them with a loop. 19.8.47

Table 19.1 Built-in functions discussed in this section


19.8.1 abs (x)

The function calculates the amount of. The parameter must be a numerical value, i.e. an instance of the data types,, or.

>>> abs (1)
1
>>> abs (-12.34)
12.34
>>> abs (3 + 4y)
5.0

19.8.2 all (iterable)

The function always returns when all elements of the iterable object passed as parameters, for example a list or a tuple, result in the truth value. It is used as follows:

>>> all ([True, True, False])
False
>>> all ([True, True, True])
True

The passed iterable object does not necessarily have to go through only instances. Instances of other data types are converted into truth values ​​according to the rules from Section 12.6.2, »Truth Values ​​of Non-Boolean Data Types«.


19.8.3 any (iterable)

The function works similarly to. It always returns when at least one element of the iterable object passed as a parameter, for example a list or a tuple, yields the truth value. It is used as follows:

>>> any ([True, False, False])
True
>>> any ([False, False, False])
False

The passed iterable object does not necessarily have to go through only instances. Instances of other data types are converted into truth values ​​according to the rules from Section 12.6.2, »Truth Values ​​of Non-Boolean Data Types«.


19.8.4 ascii (object)

The function returns a readable equivalent of the instance in the form of a string. In contrast to the built-in function that exists for the same purpose, the string returned by only contains characters from the ASCII character set:

>>> ascii (range (0, 10))
'range (0, 10)'
>>> ascii ("Püthon")
"'P \ xfcthon'"
>>> repr ("Püthon")
"'Püthon'"

19.8.5 bin (x)

The function returns a string that contains the integer passed for in its binary representation:

>>> am (123)
'0b1111011'
>>> am (-12)
'-0b1100'
>>> am (0)
'0b0'

19.8.6 bool ([x])

This creates an instance of the data type with the truth value of the instance. The truth value of is determined according to the rules specified in Section 12.6.2, »Truth Values ​​of Non-Boolean Data Types«.

If no parameter was passed, the function returns the Boolean value.


19.8.7 bytearray ([source, encoding, errors])

The function creates an instance of the data type that represents a sequence of byte values, i.e. whole numbers in the number range from 0 to 255. Note that, in contrast to, is a variable data type.

The parameter is used to initialize the byte array and can have different meanings:

If a string is passed, it is encoded into a byte sequence using the parameters and and then used to initialize the byte array. The parameters and have the same meaning as for the built-in function.

If an integer is transferred, a byte array of the length is created and filled with zeros.

If an iterable object, for example a list, is passed, the byte array is filled with the elements that iterates over. Note that these must be whole numbers in the range from 0 to 255.

In addition, a data type that supports the so-called buffer protocol can be transferred for any instance. These are, for example, the data types and themselves.

>>> bytearray ("äöü", "utf-8")
bytearray (b '\ xc3 \ xa4 \ xc3 \ xb6 \ xc3 \ xbc')
>>> bytearray ([1,2,3,4])
bytearray (b '\ x01 \ x02 \ x03 \ x04')
>>> bytearray (10)
bytearray (b '\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00')

You can find out more about the data type in Section 13.4, »Strings - str, bytes, bytearray«.

["] Note

Windows may have problems entering special characters in the command prompt. If you observe such problems, you can use IDLE to run the affected examples.

For more information, see section 13.4.4.


19.8.8 bytes ([source, encoding, errors])

This creates an instance of the data type [70] (see Section 13.4.4, »Character Sets and Special Characters«) which, like the data type, stores a sequence of byte values. In contrast to, it is an immutable data type, which is why we also speak of a -String.

As with the built-in function, the parameters, and are used to initialize the byte sequence:

>>> bytes (10)
b '\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00'
>>> bytes ([1,2,3])
b '\ x01 \ x02 \ x03'
>>> bytes ("äöü", "utf-8")
b '\ xc3 \ xa4 \ xc3 \ xb6 \ xc3 \ xbc'

19.8.9 chr (i)

The function returns a string of length 1 containing the character with the Unicode code point:

>>> chr (65)
'A'
>>> chr (33)
'!'
>>> chr (8364)
'€'

August 19, 2010 complex ([real, imag])

This creates an instance of the data type [71] (see Section 12.7, »Complex Numbers - complex«) for storing a complex number. The instance created has the complex value real + imag⋅j. Missing parameters are assumed.

It is also possible to pass a string containing the literal of a complex number to the function. In this case, however, no further parameters may be specified.

>>> complex (1, 3)
(1 + 3y)
>>> complex (1.2, 3.5)
(1.2 + 3.5j)
>>> complex ("3 + 4j")
(3 + 4y)
>>> complex ("3")
(3 + 0j)

Note that a possibly passed string must not contain any spaces around the operator:

>>> complex ("3 + 4j")
Traceback (most recent call last):
File "", line 1, in
ValueError: complex () arg is a malformed string

However, spaces at the beginning or end of the string are not a problem.


19.8.11 dict ([source])

This creates an instance of the data type [72] (see Section 14.1, »Dictionary - dict«). If no parameter is passed, an empty dictionary is created. You can use one of the following calls to fill the dictionary with values ​​when it is generated:

  • If there is a dictionary, the keys and values ​​of this dictionary are transferred to the new one. Please note that no copies of the values ​​are created, but that these continue to reference the same instances.
    >>> dict ({"a": 1, "b": 2})
    {'a': 1, 'b': 2}
  • Alternatively, it can be an object iterating over tuples, where each tuple must contain two elements: the key and the value associated with it. The list must have the structure:
    >>> dict ([("a", 1), ("b", 2)])
    {'a': 1, 'b': 2}
  • It also allows you to pass keys and values ​​as keyword arguments. The parameter name is written in a string and used as a key. Please note that this means that you are subject to the restrictions of an identifier when assigning names:
    >>> dict (a = 1, b = 2)
    {'a': 1, 'b': 2}

8/19/12 divmod (a, b)

The function returns the following tuple:. With the exception of, instances of any numeric data type can be passed for and:

>>> divmod (2.5, 1.3)
(1.0, 1.2)
>>> divmod (11, 4)
(2, 3)

8/19/13 enumerate (iterable)

The function creates an iterable object that iterates not only over the elements of, but also over tuples of the form. There is a loop counter that starts at. The loop ends when has the value. These tuple structures become clear when you convert the result of a call to a list:

>>> list (enumerate (["a", "b", "c", "d"]))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

This makes it particularly suitable for loops in which a numerical loop counter is to be carried along. Within a loop, the following can be used:

>>> for i, value inenumerate ([1,2,3,4,5]):
... print ("The value of iterable at", i, "th place is:", value)
The value of iterable at digit 0 is: 1
The value of iterable in the 1st position is: 2
The value of iterable in the 2nd position is: 3
The value of iterable in the 3rd place is: 4
The value of iterable in the 4th place is: 5

8/19/14 eval (expression, [globals, locals])

The function evaluates the Python expression in the form of a string and returns its result:

>>> eval ("1 + 1")
2

When calling, the required global and local namespace in which the expression is to be evaluated can be specified using the parameters and. If these parameters are not specified, the following is evaluated in the environment in which the call was made:

>>> x = 12
>>> eval ("x ** 2")
144
["] Note

Sometimes used to interpret user input as Python code:

>>> eval (input ("Enter Python code:"))
Enter python code: 2 ** 4
16

Please note that this use of is potentially dangerous if user input is not carefully examined. A malicious user can manipulate the program execution here.


8/19/15 exec (object, [globals, locals])

The function executes a Python code in the form of a string:

>>> code = "" "
... x = 12
... print (x ** 2)
..."""
>>> exec (code)
144

When calling, the required global and local namespace in which the code is to be executed can be specified using the parameters and. If these parameters are not specified, the code will run in the environment in which it was invoked.

["] Note

The same security warning applies to as from the previous section: Check user entries carefully before they are forwarded to!


8/19/16 filter (function, iterable)

The function expects a function object as the first and an iterable object as the second parameter. The parameter must be a function or lambda form (see Section 19.5, "Anonymous Functions") that expects a parameter and returns a Boolean value.

The function calls the function for each element of the iterable object and creates an iterable object that iterates through all elements of for which the value has returned. This should be explained with the following example, which is used to filter out the odd numbers from a list of whole numbers:

>>> filterobj = filter (lambda x: x% 2 == 0, range (21))
>>> print (list (filterobj))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

8/19/17 float ([x])

This creates an instance of the data type [73] (see Section 12.5, »Floating Point Numbers - float«). If the parameter was not specified, the value of the instance is initialized with, otherwise with the passed value. With the exception of, instances can be passed for all numeric data types.

>>> float ()
0.0
>>> float (5)
5.0

It is also possible to pass for a string that contains a floating point number:

>>> float ("1e30")
1e + 30
>>> float ("0.5")
0.5

8/19/18 format (value, [format_spec])

The function returns the value according to the format specified. For example, a monetary amount can be rounded to two decimal places as follows:

>>> format (1.23456, ".2f") + "€"
'1.23€'

For detailed information on format specifications, see Section 13.4.3 on String Formatting.


19.8.19 frozenset ([iterable])

This becomes an instance of the data type