How to fix this? ValueError: invalid literal for int() with base 10 error in Python

in Python
Python Tutorials
2 Answers to this question

The error message invalid literal for int() with base 10 would seem to indicate that you are passing a string that's not an integer to the int() function . In other words it's either empty, or has a character in it other than a digit. You can solve this error by using Python isdigit() method to check whether the value is number or not. The returns True if all the characters are digits, otherwise False .

if val.isdigit():

The other way to overcome this issue is to wrap your code inside a Python try...except block to handle this error.

Sometimes the difference between Python2.x and Python3.x that leads to this ValueError: invalid literal for int() with base 10 . With Python2.x , int(str(3/2)) gives you "1". With Python3.x , the same gives you ("1.5"): ValueError: invalid literal for int() with base 10: "1.5".

 


The reason you are getting this error is that you are trying to convert a non-integer variable into an integer. Just replace the line readings = int(readings) line with the below one.


readings = int(float(readings))

 

If you want to unleash your potential in this competitive field, please visit the Python Training Certification page for more information, where you can find the       and    Python Interview Questions FAQ's and answers    as well.

For more updates on the latest courses stay tuned to HKR Trainings.

To Top