HOME | Blog | YouTube | LinkedIn | About Me         || Calculators    | SoftEng/Tech Posts    | Code/Scripts

Python - Fractions operations in Python

Here are some basic examples setting fractions and doing some basic operations. There is also exception handling for zero division:
__author__ = 'Almir Mustafic'


from fractions import Fraction


"""
Playing around with fractions
"""


def main():
    print("main program")

    set_fractions()
    fraction_operations()
    input_and_calculate_fractions()


def set_fractions():
    print("set_fractions method ..............")

    f1 = Fraction(3, 4)
    print(f1)

    f2 = Fraction(8, 4)
    print(f2)


def fraction_operations():
    print("fraction_operations method ............. ")

    fsum = Fraction(3, 4) + Fraction(6, 4)
    print(fsum)

    my_float = float(fsum)
    print(my_float)


def input_and_calculate_fractions():
    print("input_and_calculate_fractions method ..............")

    # Enter for example: 2/3
    # Try entering 2/0 to see how it tells you that it is invalid
    try:
        a = Fraction(raw_input("enter a fraction: "))
        print(a)
        print(float(a))
    except ZeroDivisionError:
        print("Invalid fraction")

################################################

if __name__ == "__main__": main()
Here is a more complete example that allows you to interact with it. You can perform add, subtract, multiply and divide.
__author__ = 'Almir Mustafic'


from fractions import Fraction


def main():
    print("main program")
    perform_fraction_operations()


def perform_fraction_operations():
    while True:

        try:
            print("========================================================")
            fraction01 = Fraction(raw_input('Enter fraction: '))
            fraction02 = Fraction(raw_input('Enter another fraction: '))

            my_operation = raw_input('Perform one the following operations: Add (A), Subtract (S), Divide (D), Multiply (M) : ')

            print("________________________________________________________")

            if my_operation.capitalize() == 'ADD' or my_operation.capitalize() == "A":
                add(fraction01, fraction02)
            if my_operation.capitalize() == 'SUBTRACT' or my_operation.capitalize() == "S":
                subtract(fraction01, fraction02)
            if my_operation.capitalize() == 'DIVIDE' or my_operation.capitalize() == "D":
                divide(fraction01, fraction02)
            if my_operation.capitalize() == 'MULTIPLY' or my_operation.capitalize() == "M":
                multiply(fraction01, fraction02)
        except ValueError:
            print('Invalid fraction entered')
        except ZeroDivisionError:
            print("Zero division fraction. Do NOT do this :)")

        print("========================================================")

        answer = raw_input('Do you want to exit? (yes) for yes or just press enter to continue: ')
        if answer == 'yes' or answer == 'y':
            break


def add(f1, f2):
    print('Result of adding {0} and {1} is {2} '.format(f1, f2, f1+f2))


def subtract(f1, f2):
    print('Result of subtracting {1} from {0} is {2}'.format(f1, f2, f1-f2))


def divide(f1, f2):
    print('Result of dividing {0} by {1} is {2}'.format(f1, f2, f1/f2))


def multiply(f1, f2):
    print('Result of multiplying {0} and {1} is {2}'.format(f1, f2, f1*f2))


################################################

if __name__ == "__main__": main()
Almir M.




No comments:

Post a Comment