int() function in Python
Python int() function returns an integer from a given object or converts a number in a given base to decimal.
Python int() Syntax :
int(string, base)
Python int() Parameter :
- string : consists of 1’s and 0’s
- base : (integer value) base of the number.
Python int() Returns :
Returns an integer value, which is equivalent of binary string in the given base.
Python int() Exception and Errors :
TypeError : Returns TypeError when any data type other than string or integer is passed in its equivalent position.
Python int() method example
Example 1: Working with int() function in Python
Python3
# Python3 program for implementation# of int() functionnum = 13String = '187'# Stores the result value of# binary "187" and num additionresult_1 = int(String) + numprint("int('187') + 13 = ", result_1, "\n")# Example_2str = '100'print("int('100') with base 2 = ", int(str, 2))print("int('100') with base 4 = ", int(str, 4))print("int('100') with base 8 = ", int(str, 8))print("int('100') with base 16 = ", int(str, 16)) |
Output :
int('187') + 13 = 200
int('100') with base 2 = 4
int('100') with base 4 = 16
int('100') with base 8 = 64
int('100') with base 16 = 256Example 2: Convert binary string to Python int base
Python3
# Python3 program for implementation# of int() function# "111" taken as the binary stringbinaryString = "111"# Stores the equivalent decimal# value of binary "111"Decimal = int(binaryString, 2)print("Decimal equivalent of binary 111 is", Decimal)# "101" taken as the octal stringoctalString = "101"# Stores the equivalent decimal# value of binary "101"Octal = int(octalString, 8)print("Decimal equivalent of octal 101 is", Octal) |
Output :
Decimal equivalent of binary 111 is 7 Decimal equivalent of octal 101 is 65
Example 3: Program to demonstrate the TypeError
Python3
# Python3 program to demonstrate# error of int() function# when the binary number is not# stored in as stringbinaryString = 111# it returns an error for passing an# integer in place of stringdecimal = int(binaryString, 2)print(decimal) |
Output :
TypeError: int() can't convert non-string with explicit base
Example 4: Python int() Exception
Python3
try: var = "Geeks" print(int(var))except ValueError as e: print(e) |
Output:
invalid literal for int() with base 10: ‘Geeks’
Application :
It is used in all the standard conversions. For example conversion of binary to decimal, octal to decimal, hexadecimal to decimal.


