int

Full name
int
Library
Built-in
Syntax

class int([n])
class int(n, base=10)

Description

The int function returns an integer from a number or a string, or returns the value 0 if no argument is included.

If the argument is not a number or if a base is added as second argument, the first argument must be of type text, bytes or bytearray, representing an integer in the specified base. Optionally, the text could be preceded by the + or - signs (no spaces between the sign and the text are allowed). The text can include spaces at the beginning or at the end.

The default base is 10. Allowed values can be 0, and any number between 2 and 36, inclusive.

Base 2, 8, and 16 texts can optionally be preceded by the characters 0b/0B, 0o/0O, and 0x/0X respectively. If the base is zero, the text will be interpreted literally.

Parameters
  • n: (Optional if the base is not included) number or text string to convert to integer.
  • base: Base to consider during the interpretation of the text.
Examples

If the argument is a real number, the function extracts the integer part (truncating the number):

Int function. Example of use

 

Attempting to convert a complex number returns an error of type TypeError :

Int function. Example of use

 

Similarly, the attempt to convert a number (even if it is an integer) specifying the base, also returns an error of the same type:

Int function. Example of use

 

If the number is included as first argument in text format, it is possible to specify the base to use:

Int function. Example of use

 

If the text includes characters not allowed in the indicated base, an error is also returned, of type ValueError :

Int function. Example of use

 

In these examples, a text containing the representation of a number in base 2 is converted to an integer:

Int function. Example of use

If the text is preceded, as in this case, with the characters "0b", the base can take the value 0:

Int function. Example of use

If zero base is indicated, but these characters are not included at the beginning of the text, the text string is interpreted literally, applying base 10 by default:

Int function. Example of use

 

If no arguments are included, the function returns the number 0:

Int function. Example of use

 

Submitted by admin on Sun, 01/20/2019 - 14:04