Instead, you can use an augmented assignment:
>>> test = 0
>>> test += 5
>>> print(test)
5
>>>
This feature works for addition, subtraction, multiplication, division, modulus, floor division, and
exponentiation.
Calculating with Fractions
Python supports some other cool math features that you don’t often run across in other programming
languages. One of those features is the ability to work directly with fractions. This section walks
through how to work with fractions in your Python scripts.
The Fraction Object
The fractions Python module defines a special object called Fraction. The Fraction
object holds the numerator and the denominator of a fraction as separate properties of the object.
To use a Fraction object, you need to import it from the fractions module. After you import
the object class, you can create an instance of a Fraction object, like this:
Click here to view code image
>>> from fractions import Fraction
>>> test1 = Fraction(1, 3)
>>> print(test1)
1/3
>>>
The first parameter of the Fraction() method is the fraction numerator, and the second parameter
is the denominator of the fraction value. Now you can perform any type of fraction operation on the
variable, like this:
>>> result = test1 * 4
>>> print(result)
4/3
>>>
Starting in Python v3.3, the Fraction() constructor can also convert floating-point values into a
Fraction object, as in the following example:
>>> test2 = Fraction(5.5)
>>> print(test2)
11/2
>>>
Now that you know how to create fractions, the next step is to start using them in your calculations!
Fraction Operations
After you create a Fraction object, you can use any type of mathematical calculation on the object
with other Fraction objects, as in this example:
>>> test1 = Fraction(1, 3)