WORKING WITH FRACTIONS
Python supports the Fraction() function (defined in the fractions module), which accepts two integers that represent the numerator and the denominator (which must be non-zero) of a fraction. Several examples of defining and manipulating fractions 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 code samples that work with strings, the next section briefly discusses Unicode and UTF-8, both of which are character encodings.