Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

class - Using Fractions in Python

I'm using classes here to input a fraction (when given the numerator and denominator), as well as add and multiply two fractions together. For some reason, the imported fractions module only works correctly for part of the program; the gcd method works, but the Fraction method (where when given two numbers, puts into fraction format) does not work, instead throwing a NameError (specifically, "global name 'Fractions' is not defined").

What am I doing wrong? I am relatively new to Python, and any suggestions on how to make this code tighter with more exceptions would be greatly appreciated.

Here is my code:

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("
 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("
 You didn't enter two numbers.")
        # Exception for user input both or one of them, not being integers.
    except TypeError:
        print("
 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need your own class to multiply two fractions:

>>> 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)

As for the error you mentioned, it's unlikely as you don't have a name "Fractions" anywhere in your code and you didn't post a traceback. You're most likely running some old version of your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...