How to express fraction in python

藏色散人
Release: 2019-08-01 16:18:00
Original
11445 people have browsed it

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)
Copy after login

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
Copy after login

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)
Copy after login

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) >>>
Copy after login

Input decimals directly, and the Fraction method directly converts decimals into fractions.

>>> from decimal import Decimal >>> Fraction(1.1) Fraction(11, 10)
Copy after login

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!