Tags
python
Asked 3 years ago
19 Sep 2021
Views 790
Mafalda

Mafalda posted

Python - ValueError: invalid literal for int() with base 10

i try to run some code in Python but when i run below code:

interger =input('enter no:')
print(int(interger))


it giving the error as below when i enter '2.2':

 File "<stdin>", line 13, in <module>
ValueError: invalid literal for int() with base 10: '2.2'

i want to convert string or float value to integer
how to solve ValueError in Python ?
jassy

jassy
answered Sep 19 '21 00:00

int() method is used to convert string or float value to integer in Python.
but if you pass string format of float value it will generate the ValueError: invalid literal for int()

float() method is used to convert string or integer to float in Python ,
if you pass string version of the float value in the float() method, it will convert to float value

float("2.2") # it will return 2.2


so instead of passing direct string representation of float value in to int() function , pass it to float() and returned value form float pass it to int()

int(float('2.2')) # it will return 2 which is integer value of 2.2
shyam

shyam
answered Sep 19 '21 00:00

int("float value") give error means it is a bug of Python because the same string representation of the float or integer value works for float() method but not work with int() method.

float(" float value") return float value
float(float value) return float value
float("Ineteger value") return float value
float(Ineteger value) return float value
int(Ineteger value) return integer value
int("Ineteger value") return integer value
int("float value") , only this case give use error :
ValueError: invalid literal for int() with base 10
so dont user string float value in int() method.

you can see the below example:

>>> float(2/2)
1.0
>>>float(2/4)
0.5
>>> int(3/2)
1
>>> float(3.4)
3.4
>>> float(3)
3.0
>>> float("3.5")
3.5
>>> float("4")
4.0
>>> int(3.5)
3
>>> int("3.4")
Traceback (most recent call last):
 
ValueError: invalid literal for int() with base 10: 3.4
 
Post Answer