int() Builtin Function

Python – int()

Python int() builtin function is used to create an integer value from given object(usually a string, or another number), and an optional base value.

Syntax

The syntax of int() function is

int(x, base=10)

where

  • x is a string, or a number.
  • base is number using which the integer is constructed from x

If no argument is passed to int() function, then it returns 0.

Examples

Convert string to integer

In the following program, we use int() function to convert a string x into an integer.

Python Program

x = '541'
output = int(x)
print(output)
Run

Output

541

Convert string to integer with given base

In the following program, we use int() function to convert a string x into an integer, and specify the base to use while converting the value from the string into an integer.

Python Program

x = '241'
output = int(x, base=5)
print(output)
Run

Output

71

Explanation

241(5) = 2*(5^2) + 4*(5^1) + 1
       = 50 + 20 + 1
       = 71 

Convert float to integer

In the following program, we use int() function to convert a float value in x into an integer.

Python Program

x = 3.41
output = int(x)
print(output)
Run

Output

3

Summary

In this tutorial of Python Examples, we learned the syntax of int() builtin function, and how to use this function to convert given string, or number into an integer, with examples.