WORKING WITH FRACTIONS
Python supports the Fraction() function (which is define in the fractions module) that accepts two integers that represent the numerator and the denominator (which must be nonzero) of a fraction. Several example of defining and manipulating fractions in Python are shown here:
>>> from fractions import Fraction >>> a = Fraction(5, 4) >>> b = Fraction(7, 16) >>> print(a + b) 27/16 >>> print(a * b) 35/64 >>> # Getting numerator/denominator >>> c = a * b >>> c.numerator 35 >>> c.denominator 64 >>> # Converting to a float >>> float(c) 0.546875 >>> # Limiting the denominator of a value >>> print(c.limit_denominator(8)) 4 >>> # Converting a float to a fraction >>> x = 3.75 >>> y = Fraction(*x.as_integer_ratio()) >>> y Fraction(15, 4)
Before delving into Python code samples that work with strings, the next section briefly...