How to Use the Python int() Function with Examples
In this tutorial, you'll learn how to use the int() function in Python. Python int() converts a number or string (that is convertible) to an integer number.
Python int() Function Syntax
The syntax of the int() function is as follows:
int(value=0, base=10)
The int() Function Parameters
- value: A number or string that can be converted to an integer number.
- base: Base of the number. It defaults to 10 if omitted.
Remarks
- int() returns 0 if both value and base omitted.
- If the base argument not omitted, the value argument must be a string.
Examples
Convert a String to an Integer Number
The following code illustrates an example of how to convert a string to an integer number:
value = "12"
base = 10
number = int(value, base)
print (number)
Output:
12
Convert a Numeric Number to an Integer Number
The following sample code converts a numeric number to an integer number:
value = 12.40
base = 10
number = int(value, base)
print (number)
Output:
Traceback (most recent call last):
File "int.py", line 14, in
number = int(value, base)
TypeError: int() can't convert non-string with explicit base
Here, as you can see, Python threw an error because the base argument was given, but the value argument was not a string.
Here is an example of the program that converts a numeric number to an integer number:
value = 12.90
base = 10
number = int(value)
print (number)
Output:
12
Convert a String Representing a Binary Number
The following sample code converts a string that represents a binary number to an integer number:
value = "1110"
base = 2
number = int(value, base)
print("Number equivalent of binary 1110 is", number)
Output:
Number equivalent of binary 1110 is 14
In this tutorial, you've learned how to use the int() function in Python. The int() function is a function to convert a number or string (that is convertible) to a number to an integer number.