w3resource

Python Math: Add, subtract, multiply and divide two fractions


46. Arithmetic on Fractions

Write a Python program to add, subtract, multiply and divide two fractions.

Sample Solution:

Python Code:

import fractions

f1 = fractions.Fraction(2, 3)
f2 = fractions.Fraction(3, 7)

print('{} + {} = {}'.format(f1, f2, f1 + f2))
print('{} - {} = {}'.format(f1, f2, f1 - f2))
print('{} * {} = {}'.format(f1, f2, f1 * f2))
print('{} / {} = {}'.format(f1, f2, f1 / f2))

Sample Output:

2/3 + 3/7 = 23/21                                                                                             
2/3 - 3/7 = 5/21                                                                                              
2/3 * 3/7 = 2/7                                                                                               
2/3 / 3/7 = 14/9

Flowchart:

Flowchart: Add, subtract, multiply and divide two fractions

For more Practice: Solve these Related Problems:

  • Write a Python program to perform addition, subtraction, multiplication, and division on two Fraction instances and print each result.
  • Write a Python function that accepts two fractions, computes the four basic arithmetic operations, and returns a dictionary of results.
  • Write a Python script to prompt the user for two fractions, perform all arithmetic operations, and then display the outcomes in a formatted manner.
  • Write a Python program to validate the results of fraction arithmetic by comparing them with float approximations and printing both.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create the fraction instances of decimal numbers.
Next: Write a Python program to convert a floating point number (PI) to an approximate rational value on the various denominator.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.