Fractions Calculator Project

Fractions Project with Python

Write a Python program that performs addition and subtraction operations on fractions. The program should specifically calculate the following operations:

1. Addition: 9/7 + 8/6.
2. Subtraction:  160/4 – 65/15

Ensure that your program does not use any external libraries for the calculations. Additionally, make sure to print out the fractions involved in each calculation, along with the corresponding result.

Steps

  1. Define a function to find the greatest common divisor (GCD) and the least common multiple (LCM) of two numbers. You can use the Euclidean algorithm to find the GCD.
  2. Create a function to simplify fractions by dividing the numerator and denominator by their GCD.
  3. Write functions to add and subtract fractions. These functions should find the common denominator, perform the operation, and then simplify the result.
  4. Perform the calculations for the given operations using the defined functions.
  5. Print out the input fractions and the result of the calculations.

More Python practice here.

Expected output

The result of (9, 7) + (8, 6) is (55, 21)
The result of (160, 4) - (65, 15) is (107, 3)

Source code

#Define a function to find the greatest common divisor 
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    return (a * b) // gcd(a, b)

# Define a function to simplify fractions
def simplify_fraction(numerator, denominator):
    common = gcd(numerator, denominator)
    return numerator // common, denominator // common

def add_fractions(fraction1, fraction2):
    num1, den1 = fraction1
    num2, den2 = fraction2
    lcd = lcm(den1, den2)
    new_num = num1 * (lcd // den1) + num2 * (lcd // den2)
    return simplify_fraction(new_num, lcd)

def subtract_fractions(fraction1, fraction2):
    num1, den1 = fraction1
    num2, den2 = fraction2
    lcd = lcm(den1, den2)
    new_num = num1 * (lcd // den1) - num2 * (lcd // den2)
    return simplify_fraction(new_num, lcd)

# Given fractions
fraction1_add = (9, 7)
fraction2_add = (8, 6)
fraction1_sub = (160, 4)
fraction2_sub = (65, 15)

# Perform addition and subtraction
result_add = add_fractions(fraction1_add, fraction2_add)
result_sub = subtract_fractions(fraction1_sub, fraction2_sub)

# Print the input fractions and the results
print(f"The result of {fraction1_add} + {fraction2_add} is {result_add}")
print(f"The result of {fraction1_sub} - {fraction2_sub} is {result_sub}")

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart