Tuesday, February 8, 2011

Python - working with fractions

# Add, Subract, Multiply or Divide Fractions with python
 
# use the built in python Fraction module
from fractions import Fraction
 
print("Enter two fractions.")
 
# Get the two fractions
a = Fraction(input("Enter the first fraction: "))
b = Fraction(input("Enter the second fraction: "))
 
print("Add: ", a + b)
print("Subtract: ", a - b)
print("Multiply: ", a * b)
print("Divide: ", a / b)
 
# my output:
## Enter two fractions.
## Enter the first fraction: 1/2
## Enter the second fraction: 2/5
## Add:  9/10
## Subtract:  1/10
## Multiply:  1/5
## Divide:  5/4
 
 

No comments:

Post a Comment