Python For Kids For Dummies
Book image
Explore Book Buy On Amazon

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)

About This Article

This article is from the book:

About the book author:

Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started to help teach his oldest child to code. He maintains it to help other young people learn Python.

This article can be found in the category: