#How to output fraction form in python?
Python fraction representation and writing method
The Fraction function is a module (module) that implements fractions in python. The module is written by others and can Code programs that are used directly, including definitions of classes, functions, and labels, are part of the Python standard function library. The module must be inserted first to use it.
>>> from fractions import Fraction #插入模块 >>> f =Fraction(1,2) #创建Fraction 类,并初始化为1/2 >>> f #输出分数类对象Fraction(1, 2)
Related recommendations: "Python Tutorial"
When entering fractions, the first letter of Fraction must be capitalized, otherwise an error will be reported. We operate on fractions.
>>> Fraction(2,8)+1+1.5 2.75
If the float data type appears during the operation, the final result will be float type data. If there are only integer types and fraction types in the operation expression, the output result will be of type fraction.
>>> Fraction(2,8)+Fraction(2,5)+3 Fraction(73, 20)
Fraction() method is very interesting, it can directly receive the fraction string and turn it into input. Note that the entered fraction must be enclosed in quotation marks.
>>> a = Fraction('1/5') >>> a Fraction(1, 5) >>>
Input decimals directly, and the Fraction method directly converts decimals into fractions.
>>> from decimal import Decimal >>> Fraction(1.1) Fraction(11, 10)
To convert a string into a decimal, you need to use the decimal class, and then convert the decimal into a fraction.
>>> from decimal import Decimal >>> Fraction(Decimal('1.1')) Fraction(11, 10)
First convert the 1.1 string into a decimal, and then into a fraction.
Extensions:
Python: Fraction operations
fractions module can be used to perform mathematical operations involving fractions
>>> from fractions import Fraction >>> a = Fraction(5, 4) >>> b = Fraction(7, 16) >>> print(a + b) 27/16 >>> print(a * b) 35/64 >>> # Getting numerator/denominator >>> c = a * b >>> c.numerator 35 >>> c.denominator 64 >>> # Converting to a float >>> float(c) 0.546875
Generally not used in most programs There will be problems with calculating fractions, but sometimes they still need to be used. For example, in a program that allows you to accept test units in the form of fractions and perform operations as fractions, using fractions directly can reduce the work of manual conversion to decimals or floating point numbers
The above is the detailed content of How to output fraction form in python. For more information, please follow other related articles on the PHP Chinese website!