Home »
Python »
Python Reference »
Python Built-in Functions
Python int() Function: Use, Syntax, and Examples
By IncludeHelp Last updated : December 07, 2024
Python int() function
The int() function is a library function in Python, it is used to convert a string (that should contain a number/integer), number (integer, float) into an integer value.
Consider the below example with sample input/output values:
Input:
a = "1001"
print(int(a))
Output:
1001
Input:
a = 10.23
print(int(a))
Output:
10
Input:
a = "1110111"
print(int(a,2))
Output:
119
Syntax
The following is the syntax of int() function:
int(value, [base=10])
Parameter(s):
The following are the parameter(s):
- value – source value (string, number(integer/float)) to be converted in an integer value.
- base – it’s an optional parameter with default 10, it is used to define the base of source value, for example: if source string contains a binary value then we need to use base 2 to convert it into an integer.
Return Value
The return type of int() function is <type 'int'>, it returns an integer value.
Python int() Example 1: Convert values to integer
# python code to demonstrate example
# of int() function
a = 10.20
b = "1001"
c = "000"
print("a: ", a)
print("int(a): ", int(a))
print("b: ", b)
print("int(b): ", int(b))
print("c: ", c)
print("int(c): ", int(c))
Output
a: 10.2
int(a): 10
b: 1001
int(b): 1001
c: 000
int(c): 0
Python int() Example 2: Convert different number systems to integer
Python code to convert different numbers systems (binary, octal and hexadecimal) to integer value (decimal).
# python code to demonstrate example
# of int() function
a = "10101010"
print("a: ", int(a,2))
a = "1234567"
print("a: ", int(a,8))
a = "5ABC12"
print("a: ", int(a,16))
Output
a: 170
a: 342391
a: 5946386
Python int() Example 3: Input integer value
The user input can be done by using the input() function and it returns a string. To input an integer number, we have to convert the value returned by the input() function into an integer using the int() function.
# Python int() Example - Input integer value
# Inputs
age = int(input("Enter age: "))
luckynumber = int(input("Enter you lucky number: "))
# Printing the values
print("age:", age)
print("luckynumber:", luckynumber)
Output
Enter age: 21
Enter you lucky number: 108
age: 21
luckynumber: 108
Python int() Example 4: ValueError
If the given value is not a valid integer, the function returns a ValueError.
# Python int() Example
# ValueError
x = int("Hello") # ValueError
Output
Traceback (most recent call last):
File "/home/main.py", line 4, in <module>
x = int("Hello") # ValueError
ValueError: invalid literal for int() with base 10: 'Hello'