2

I am running some code in which I am expecting user to insert fraction which will be computed and stored as a float value in a variable.

I am using the following command. It works fine when I give input such as 4.5:

a = float(input('>> '))

But something like 3/4 gives me an error. I know what the problem is, I would like to know if there is an alternative way to input a fraction which gets solved and stored as a float in a variable.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
PushkarKadam
  • 269
  • 2
  • 4
  • 9
  • `'3/4'` isn't the representation of a floating point number. If you are allowing the user to enter fractions, you will need to parse them yourself. – jonrsharpe Jan 20 '17 at 17:10
  • read the input as a string then apply the solution described in the answer to this question: http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – Dale Wilson Jan 20 '17 at 17:11
  • https://docs.python.org/3/library/fractions.html – Josh Lee Jan 20 '17 at 17:12

1 Answers1

3

As noted by Josh Lee, wrap it in a Fraction (from fractions import Fraction) and then cast it to float:

r = float(Fraction(input(">>> ")))

this accept floats and strings that have a form of:

[sign] numerator ['/' denominator] 

as noted in its docs.

You should of course wrap it in a try-except to guard against unexpected input that doesn't abide to that form.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • It may be worth _not_ converting the resulting Fraction to float if the application can deal with that, as a Fraction doesn't lose precision and stays maximally precise as long as the operations done on it leave it as a Fraction. – blubberdiblub Jan 20 '17 at 22:06