user7551342
user7551342

Reputation:

Python - Output fraction instead of decimal

So I am trying to make a piece of code that calculates the slope of a line. I am using 3.6.

    y1 = float(input("First y point: "))
    y2 = float(input("Second y point: "))
    x1 = float(input("First X point: "))
    x2 = float(input("Second X point: "))

    slope = (y2 - y1)/(x2 - x1)

    print("The slope is:",slope)

Whenever I put in numbers that make the answer irrational, the answer comes to be a decimal. Is it possible to keep it as a fraction?

Upvotes: 5

Views: 11587

Answers (1)

Kirill Bulygin
Kirill Bulygin

Reputation: 3836

Yes, see https://docs.python.org/3.6/library/fractions.html (but a numerator and a denominator should be rational in this case, e.g. integer):

from fractions import Fraction

y1 = int(input("First y point: "))
y2 = int(input("Second y point: "))
x1 = int(input("First X point: "))
x2 = int(input("Second X point: "))

slope = Fraction(y2 - y1, x2 - x1)

print("The slope is:", slope, "=", float(slope))

Input and output:

First y point: 5
Second y point: 7
First X point: 10
Second X point: 15
The slope is: 2/5 = 0.4

Upvotes: 8

Related Questions