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.

In this tutorial, you will learn the syntax of int() function, and then its usage with the help of example programs.

Syntax

The syntax of int() function is

int(x, base=10)

where

ParameterDescription
xA string, or a number.
baseA number using which the integer is constructed from x.

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

Examples

1. 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 Code Copy

Output

541

2. 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 Code Copy

Output

71

Explanation

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

3. 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 Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍