Python 2: ValueError: invalid literal for int () with base 10: '20 .0 '

I have a little math problem in python. Therefore, I have several variables, x , y and answer :

 >>>x = 20 >>>y = 21 >>>answer = x / y * 100 >>>answer 0 

This way it outputs null. OK I know that it prints zero, because I had to print x = 20.0 instead of printing x = 20 .

But I still need to print:

 95.2380952381 

How can i do this?

Note. Can't I just write x = 20.0 ?

And also I tried to do it like this:

 x1 = str(x) + '.0' result = int(x1) / y * 100 

But Python will tell me the error:

 ValueError: invalid literal for int() with base 10: '20.0' 

So how can I fix this?

+4
source share
4 answers

Use from __future__ import division to make the whole float separation.

Alternatively, instead of int() use float() to interpret the string as a floating-point number:

 answer = float(x) / y * 100 
+2
source

Just use

 >>> answer = float(x) / y * 100 
0
source

use float(x)/y*100 instead of int()

but that would only fix the error, but what you tried to achieve can be done in this way
answer = x/y*100.

0
source

Python thinks you're doing integer division (since x , y are integers). To fix this, you can use float() to convert one of x or y to float .:

 answer = float(x) / y * 100 
0
source

Source: https://habr.com/ru/post/1492388/


All Articles