# python类分数(python class fraction numbers)

   import sys

class Rational:

def __init__(self,n,d):
self.numerator= n
self.denominator= d
def value(self):
return float(self.numerator)/float(self.denominator)

def __repr__(self):
return "%d/%d ~ %g" % (self.numerator,self.denominator,self.value())
def read(self):
while 1:
try:
s=raw_input("Enter fraction n/d: ")
n,d= s.split("/")
self.numerator= int(n)
self.denominator= int(d)
except KeyboardInterrupt:
print
exit()
except:
print sys.exc_info()[0]
print "bad input, try again."
else:
if int(d)==0:
print "The denominator cannot be zero. Try again."
elif int(d)<0:
print "The denominator cannot be negative. Try again."
else:
return

r1=Rational(1,1)
r1.read()
print r1

r2=Rational(1,1)
r2.read()
print r2


>>> import fractions
>>> fractions.Fraction(2, 4)
Fraction(1, 2)


def gcd(a, b):
while b:
a, b = b, a%b
return a

g = gcd(numerator, denominator)
numerator //= g
denominator //= g


    >>> num = 2
>>> den = 4
>>> from fractions import Fraction
>>> frac = Fraction(num,den).limit_denominator()
>>> numer = frac.numerator
>>> denom = frac.denominator
>>> print '%d/%d ~ %g' % (numer, denom, float(numer)/denom)
1/2 ~ 0.5


import fractions

f = fractions.Fraction(5, 10)
print (f) # print 1/2