I'm trying to make it so if the denominator of the fraction is over 2, it prints the decimal. Else, it prints the fraction
from fractions import Fraction
z = float(input())
frac = (Fraction(z))
s = str(z)
x = s.find("/")
x1 = x + 1
segment = z[x1:]
print(segment)
if len(segment) <= 3:
print(frac)
else:
print(z)
You are making it way harder than it needs to be. Use the denominator
attribute of the Fraction
instance:
frac = Fraction(z)
if frac.denominator > 2:
print(z)
else:
print(frac)
You may want to use the Fraction.limit_denominator()
method to account for the imprecise nature of floats:
frac = Fraction(z).limit_denominator()
if frac.denominator > 2:
print(z)
else:
print(frac)
Fraction.limit_denominator()
finds the closest fraction to the original where the denominator is limited be below 1 million:
>>> from fractions import Fraction
>>> 2/3
0.6666666666666666
>>> Fraction(2/3)
Fraction(6004799503160661, 9007199254740992)
>>> Fraction(2/3).limit_denominator()
Fraction(2, 3)
Another alternative is to pass the user input straight to Fraction()
; the constructor accepts both valid values for float()
and strings in the form of numerator / denominator (with optional sign). This would let your users input exact fractions such as '2 / 3':
z = Fraction(input()).limit_denominator()
if frac.denominator > 2:
print(float(z))
else:
print(frac)