How to represent rational numbers in Python

Overview

There are two types of division in Python:

  1. Floating-point division: When we use the / operator to divide two integer numbers (x/y), we will get a floating-point number as the result.

  2. Floor division: When we use the // operator to divide two integers (x//y), we will get an integer number. This type of division is also known as integer division.

Note: In mathematics, a rational number can be expressed as a fraction pq\dfrac{p}{q}, where pp is an integer in the numerator and qq is an integer in the denominator, and qq \neq 0.

In Python, rational numbers exist and can be represented with the use of the fractions module. To use this module, we have to first import it into our program by running the following command:

from fractions import Fraction

Syntax

Fraction(22,7)

Parameters

In the Fraction() constructor, the first parameter is the numerator, and the second parameter is the denominator.

Code

from fractions import Fraction
print(Fraction(22,7))

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved