SoFunction
Updated on 2025-03-03

A brief introduction to the usage of built-in Python functions int

int() is a built-in function in Python, mainly used to convert other types of data into integers. This article will elaborate on its usage from multiple aspects.

1. Basic usage

The int() function can convert a string with a number into an integer. for example:

age = int('18')

The above code converts the string '18' into an integer and assigns it to the variable age.

In addition, the int() function can also convert other data types into integers, such as floating point numbers:

num = int(3.14)

The above code converts the floating point number 3.14 into an integer and assigns it to the variable num.

2. Calculation conversion

The int() function can convert other binary numbers into decimal numbers. For example, convert the binary number 1101 to a decimal number:

num = int('1101', 2)
print(num) # Output:13

Where, the second parameter 2 means that the string '1101' is to be converted as a binary number.

Similarly, convert the hexadecimal number 0x1A into a decimal number:

num = int('1A', 16)
print(num) # Output:26

Among them, the second parameter 16 indicates that the string '1A' is to be converted as a hexadecimal number.

3. Exception handling

When converting the int() function, if it encounters a data type that cannot be converted, an exception will be thrown. Therefore, we can use this feature to perform exception handling.

For example, we could write a function that converts a string to an integer, and return 0 if it fails:

def str_to_int(s):
    try:
        return int(s)
    except:
        return 0

In the above code, we use the try-except statement, and if an exception is encountered during conversion, it returns 0.

4. Other usages

In addition to the above commonly used uses, the int() function has other uses, such as:

1. Convert Boolean True to integer 1 and False to integer 0:

print(int(True))  # Output: 1print(int(False)) # Output:0

2. Convert the iterable object to an integer. If the iterable object contains non-numeric elements, an exception will be thrown:

print(int([1, 2, 3])) # Output: 123print(int([1, 2, 'a'])) # throw an exception

Attachment: Advanced usage of Python built-in function int()

The int() function can convert real number types into integers and round down, that is, round left on the number axis. It is simple and crude, and has code to prove it:

>>> int(3.6)
3
>>> int(3.4)
3

In addition, int() can also convert the string into an integer in the specified binary. If the binary is not specified, the default is decimal, unless the first parameter string implies the binary and the second parameter is specified as 0, for example:

>>> int('3333')
3333
>>> int('3333', 0)
3333
>>> int('0o333', 0)
219

>>> int('0x3333', 0)
13107

So what else is there int() the second parameter besides 0? Let Python's built-in function help() tell us (essential skills to learn Python):

>>> help(int)
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 | 
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 | 
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.

That is to say, the second parameter of the int() function can be a number between 0 or 2-36 (if the first parameter string implies a binary string, it must be unified), for example:

>>> int('1111', 2)
15
>>> int('1111', 3)
40
>>> int('1111', 8)
585
>>> int('1111', 27)
20440

What's the use of such a thing? Let's tell a story: Avanti plays chess with the king. The king said that if he loses, he can take out whatever Avanti wants. Afanti said, "Let's order rice." There are 64 small grids in the chessboard. Put 1 grain of rice in the first grid, 2 grains in the second grid, 4 grains in the third grid, 8 grains in the fourth grid, and so on. The rice in each grid in the latter grid is twice as big as in the previous grid, and all 64 grids are filled. How many grains of rice do you need? Of course, this problem is easy to calculate using list comprehensions or generator expressions. However, using the int() function is perhaps the fastest.

>>> int('1'*64, 2)
18446744073709551615

Summarize

This article explains the usage of the int() function in Python in detail. In addition to basic conversion of strings and floating-point numbers into integers, we also introduce advanced usages such as how to perform binary conversion and exception handling. Mastering these usages can make us more flexible and efficient when writing Python programs.

This is the article about the usage of int() built-in Python function. For more related content on int() in Python, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!