We can get this error when trying to convert a variable to an integer.
Some examples are:
Trying to convert a string to an integer.
rana@brahma:~$ python3 Python 3.5.2 (default, Oct 8 2019, 13:06:37) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print(int("dawd")) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'dawd'
Trying to convert a float string to an integer.
>>> print(int("110.0")) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '110.0' >>>
Trying to convert an empty string to an integer.
>>> print(int("")) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '' >>>
int()
is the python's inbuilt function which converts the given number or string into an integer. Signature of this function is:int(x=0)
The default parameter is 0 which is also the default return value if no value is passed.
>>> print(int()) 0 >>>
Also, the default base to convert to is base 10.
int(x, base=10)
If base is specified, then int()
function tries to convert the given parameter to an integer in the given base.
>>> print(int('110', base=2)) 6 >>>
If a float is passed to int()
function then it returns the truncated value.
>>> print(int(110.10)) 110 >>>
isinstance
method.>>> isinstance(10, int) True >>> isinstance(10, float) False >>> isinstance(10.1, int) False >>> isinstance(10.1, float) True >>>
try-except
block to handle the error.>>> try: ... a = int('adwdaw') ... except: ... print('error in converting the variable') ... error in converting the variable >>>
If you are trying to convert a float string to an integer, you need to first convert it to float and then to an integer.
>>> text = '101.10' >>> int(text) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '101.10' >>> >>> f = float(text) >>> f 101.1 >>> int(f) 101 >>>