Python Math: Exercise-46 with Solution
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:
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.
Python: Tips of the Day
Summing a sequence of numbers [calculating the sum of zero to ten with skips]:
>>> l = range[0,10,2] >>> sum[l] 20
Home / Python Examples / Python Program to Add Subtract Multiply and Divide two numbers
In this tutorial, we will write a Python program to add, subtract, multiply and divide two input numbers.
Program to perform addition, subtraction, multiplication and division on two input numbers in Python
In this program, user is asked to input two numbers and the operator [+ for addition, – for subtraction, * for multiplication and / for division]. Based on the input, program computes the result and displays it as output.
To understand this program you should know how to
get the input from user and the basics of if..elif..else statement.
# Program published on //beginnersbook.com # Python program to perform Addition Subtraction Multiplication # and Division of two numbers num1 = int[input["Enter First Number: "]] num2 = int[input["Enter Second Number: "]] print["Enter which operation would you like to perform?"] ch = input["Enter any of these char for specific operation +,-,*,/: "] result = 0 if ch == '+': result = num1 + num2 elif ch == '-': result = num1 - num2 elif ch == '*': result = num1 * num2 elif ch == '/': result = num1 / num2 else: print["Input character is not recognized!"] print[num1, ch , num2, ":", result]
Output 1: Addition
Enter First Number: 100 Enter Second Number: 5 Enter which operation would you like to perform? Enter any of these char for specific operation +,-,*,/: + 100 + 5 : 105
Output 2: Division
Enter First Number: 20 Enter Second Number: 5 Enter which operation would you like to perform? Enter any of these char for specific operation +,-,*,/: / 20 / 5 : 4.0
Output 3: Subtraction
Enter First Number: 8 Enter Second Number: 7 Enter which operation would you like to perform? Enter any of these char for specific operation +,-,*,/: - 8 - 7 : 1
Output 4: Multiplication
Enter First Number: 6 Enter Second Number: 8 Enter which operation would you like to perform? Enter any of these char for specific operation +,-,*,/: * 6 * 8 : 48
Related Python Examples:
1. Python program to add two matrices
2. Python program to add two binary numbers
3. Python program to
add two numbers
4. Python program to swap two numbers
Doing fractions or math using Python is not something new, but I was anxious to try it out because my kids have been learning fractions in school. So I wanted to be that super dad who can solve the fractions very quickly or at least I could use it to verify their homework.
Here are samples that you can copy and paste into your text editor and try out without needing to do any modifications. These examples are tested in Python 2.7.13 in Mac OS.
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[]
Thank you for reading. Please follow me here on Medium or check out my personal blog.
Almir Mustafic
Personal Blog: //www.almirsCorner.com