Python int() Function Tutorial

Python provides the int() function in order to convert different types into the integer number. Generally, the string type is used to convert into an integer with the int() function. In this tutorial, we examine different ways to use int() function.

int() Function Syntax

The int() function has the following simple syntax.

int(VAL,BASE)
  • VAL is the value we want to convert into integer.
  • BASE is the base for the number. BASE is optional and if not provided base 10 is used by default.

Convert String To Integer (int)

One of the most popular ways of using int() function is converting a string into integer (int) . In the following example, we convert string values and string variables into integers.

number = "33"

n = int(number)

b = int("33")

Convert Float To Integer (int)

The int() function can be also used to convert floating-point numbers into integers. When a floating-point number is converted into an integer the floating-point part is rolled into an integer.

f = 33.3

# n will be 33
n = int(f)

# b will be 33
b=int(33.3)

Convert Hexadecimal

The int() function can be also used to convert into a hexadecimal number. By default, the int() function converts into decimal but we can provide different bases like hexadecimal.

number = "33"

n = int(number,16)

b = int("33",16)

Convert Binary

As we can specify the base we can use the int() function in order to convert it into binary.

number = "33"

n = int(number,2)

b = int("33",2)

int() Function Exception “invalid literal for int() with base 10:”

Well up to now we have provided number characters or strings into the int( function. But sometimes the provided string can be non-number where which will raise an exception.

s = "pythontect"

n = int(s)

Leave a Comment