Home>Article>Backend Development> How to express fraction in python
How to express fractions in Python?
The Fraction function is a module (module) in python that implements fractions. A module is a code program written by others and can be used directly, including the definition of classes, functions and labels. It is 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)
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.
Related recommendations: "Python Tutorial"
The above is the detailed content of How to express fraction in python. For more information, please follow other related articles on the PHP Chinese website!