Use Python to Help with Your Math Homework - dummies

Use Python to Help with Your Math Homework

By Brendan Scott

Part of Python For Kids For Dummies Cheat Sheet

Python can do fractions so you can check your homework answers. Use the fractions module, and its Fraction object, specifying the numerator and denominator. To get one-half, type fractions.Fraction(1, 2). For four-fifths, type fractions.Fraction(4, 5):

>>> import fractions
>>> one_half = fractions.Fraction(1, 2)
>>> one_fifth = fractions.Fraction(1, 5)

Fractions can do normal fraction calculations (including multiplication and division) for you:

>>> one_half+one_fifth
Fraction(7, 10)
>>> one_half-one_fifth
Fraction(3, 10)
>>> one_half*one_fifth
Fraction(1, 10)
>>> one_half/one_fifth
Fraction(5, 2)