Contents
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
Parameter | Description |
---|---|
x | A string, or a number. |
base | A 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.
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.
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.
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.