Exception of int() in Python
TypeError: raises TypeError when any object that does not have __int__() or __index__() Python magic methods implemented.
ValueError: raises ValueError when any object cannot be converted to an integer.
TypeError: int() can’t convert non-string with explicit base
In this example, we are trying to convert a binary number to a decimal number using the Python int() function. But this code will raise an error as the binary number passed is not in a single quote.
Python3
print ( int ( 0b101 , 2 )) |
Output :
TypeError: int() can't convert non-string with explicit base
ValueError: invalid literal for int() with base 10: ‘geeks’
This example will generate a value error as we are passing a Python String to the int() function.
Python3
print ( int ( 'geeks' )) |
Output:
ValueError: invalid literal for int() with base 10: 'geeks'
Python int() Function
Python int() function returns an integer from a given object or converts a number in a given base to a decimal.
Example:
In this example, we passed a string as an argument to the int() function and printed it.
Python3
age = "21" print ( "age =" , int (age)) |
Output:
age = 21