在Python中使用分数

2024-04-28 15:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里使用类来输入一个分数(当给定分子和分母时),以及将两个分数相加和相乘。出于某种原因,导入的分数模块只对程序的一部分正确工作;gcd方法工作,但是分数方法(当给定两个数字时,放入分数格式)不工作,而是抛出一个NameError(特别是“未定义全局名称‘分数’)。

我做错什么了?我对Python还比较陌生,对于如何在出现更多异常的情况下使代码更紧凑的建议,我将非常感激。

这是我的代码:

import fractions

class FractionClass:
    # Initialize starting numerator and denominator.
    n = 0
    d = 0
    def __init__(self, numerator, denominator):
        self.n = numerator
        self.d = denominator

    # Function that adds fractions, whichs throws NameError if gcd() doesn't work!  
    def add_fractions(self, other):
        try:
            sum_numerator = self.n + other.n
            sum_denominator = fractions.gcd(self.d, other.d)
            return(sum_numerator, sum_denominator)
        except NameError:
            print("Methods aren't defined.")

    # Function that multiplies fractions, whichs throws NameError if gcd() doesn't work!    
    def multiply_fractions(self, other):
        try:
            product_numerator = self.n * other.n
            product_denominator = self.d * other.d
            return(product_numerator, product_denominator)
         except NameError:
            print("Methods aren't defined.")

    # Enter input function.
def user_input():
    try:
        print("Enter a numerator and denominator:")
        n, d = [int(x) for x in input().split()]
        print("Enter a numerator and denominator:")
        n2, d2 = [int(x) for x in input().split()]
        # Check used to debug for denominators that aren't the minimum of 1 (0 can't be divided!)
        check = 1 / d 
        check = 1 / d2 
        # print(check)

        # Exception for d = 0.
    except ZeroDivisionError:
        print("\n You didn't enter the minimum denominator.")
        print("Set denominator to minimum default.")
        d = 1
        # Exception for not entering a space in between numbers.
    except UnboundLocalError:
        print("You didn't enter your numbers in properly! Try again.")
        # Exception for not entering all required.
    except NameError:
        print("\n You didn't enter two numbers.")
        # Exception for user input both or one of them, not being integers.
    except TypeError:
        print("\n You didn't enter all valid numbers.")
        # General exception case.
    except:
        print("Something went wrong!")

    fract = FractionClass(n,d)
    another_fraction = FractionClass(n2, d2)
    total_sum = fract.add_fractions(another_fraction)
    # Unpacks total sum tuple.
    # Puts in fraction format.
    sum_numerator, sum_denominator = total_sum
    add_output = fractions.Fraction(sum_numerator, sum_denominator)
    total_product = fract.multiply_fractions(another_fraction)
    # Unpacks product sum tuple.
    # Puts in fraction format.
    product_numerator, product_denominator = total_product
    multiply_output = fractions.Fraction(product_numerator, product_denominator)
    print(add_output, multiply_output)

Tags: inselfforinputproduct分数sumother
2条回答

你不需要自己的类来乘两个分数:

>>> from fractions import Fraction as F
>>> F("1/2")
Fraction(1, 2)
>>> F("3/4")
Fraction(3, 4)
>>> F("1/2") * F("3/4")
Fraction(3, 8)
>>> F("1/2") + F("3/4")
Fraction(5, 4)
>>> F(5, 8) + F(4, 7)
Fraction(67, 56)

至于你提到的错误,这是不太可能的,因为你没有一个名字“分数”在你的代码任何地方,你没有张贴回溯。你很可能在运行一些旧版本的代码。

第26行还有一个空格:

         except NameError:

应该是

        except NameError:

您还应该检查并修复缩进。否则,就没有身体——什么都不叫。

相关问题 更多 >