Python built-in Method - int()

w‮i.ww‬giftidea.com

The int() method in Python is a built-in function that converts a string or a number to an integer.

The syntax for int() is as follows:

int(x, base=10)

Here, x is the value to be converted to an integer, and base is the base of the number system used in x. By default, base is set to 10.

For example:

a = int("123")       # converts the string "123" to the integer 123
b = int(3.14)        # converts the float 3.14 to the integer 3
c = int("1010", 2)   # converts the binary string "1010" to the integer 10
d = int("0xFF", 16)  # converts the hexadecimal string "0xFF" to the integer 255

In the example above, we use the int() function to convert various strings and numbers to integers. In the third example, we use the base parameter to specify that the input string is in binary format. In the fourth example, we use the base parameter to specify that the input string is in hexadecimal format.

The int() function is useful when you need to convert a string or a floating-point number to an integer for mathematical calculations or comparison operations. Note that if the input value cannot be converted to an integer, a ValueError exception is raised.

If you need to convert a number to a string in a different number system, such as binary or hexadecimal, you can use the bin(), oct(), or hex() built-in functions, respectively.