Home »
Python
int() function with example in Python
Python int() function: Here, we are going to learn about the int() function in Python with example.
Submitted by IncludeHelp, on April 01, 2019
Python int() function
int() function is used to convert a string (that should contain a number/integer), number (integer, float) into an integer value.
Syntax:
int(value, [base=10])
Parameter:
- 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: int – returns an integer value.
Example:
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
Python code to convert values to an 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 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
ADVERTISEMENT
ADVERTISEMENT