ValueError: could not convert string to float: '8/3'

Question:

I am having the folllowing instruction

x1,y1,x2,y2,x3,y3,xp,yp = map(float, input().split())

When I am trying to execute it for a fractional value, e.g. 8/3, I get an error message.

x1,y1,x2,y2,x3,y3,xp,yp = map(float, input().split())
0.1 0.2 -8 -16.67 0 0.1 8/3 1
# output
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    x1,y1,x2,y2,x3,y3,xp,yp = map(float, input().split())
ValueError: could not convert string to float: '8/3'

What am I doing wrong here? Thanks in advance for any kind of help.

Asked By: Dimitris

||

Answers:

8/3 is not a valid notation for a python float. However, you can parse these inputs using the fractions module:

>>> import fractions
>>> inp = '0.1 0.2 8/3 1/2 -5/10'
>>> [float(fractions.Fraction(s)) for s in inp.split()]
[0.1, 0.2, 2.6666666666666665, 0.5, -0.5]
Answered By: gog

The string 8/3 can’t be converted using float, just use something from fractions module.

Answered By: FLAK-ZOSO
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.