pythonmathimportformatfractions

How to print out whole numbers alongside fractions in Python using fraction import


Im trying to print out a whole numbers alongside rational fractions

E.g: 3 1/2 , **not **7/2

I wanted to try to use if statements like if num1 >= den1: whole +=

though i was afraid that wasnt gonna work or mess up everything else i wrote in the code

import fractions

num1 = int(input('Enter 1st number Numerator: '))
den1 = int(input('Enter 1st number Denominator: '))

num2 = int(input('Enter 2nd number Numerator: '))
den2 = int(input('Enter 2nd number Denominator: '))

f1 = fractions.Fraction(num1, den1)
f2 = fractions.Fraction(num2, den2)

equ = str(input('Select Operation, +, * or /?: '))

if equ == '*':
  print('{} * {} = {}'.format(f1, f2, f1 * f2))

if equ == '/':
    print('{} / {} = {}'.format(f1, f2, f1 / f2))

if equ == '+':
    print('{} + {} = {}'.format(f1, f2, f1 + f2))

the output is always

1/4 + 5/4 = 3/2

not

1/4 + 5/4 = 1 1/2


Solution

  • To print the output in the format you desire, you can extract the whole number and the fractional part separately and format the output accordingly. Here's a code you can use to do this:

    import fractions
    
    num1 = int(input('Enter 1st number Numerator: '))
    den1 = int(input('Enter 1st number Denominator: '))
    
    num2 = int(input('Enter 2nd number Numerator: '))
    den2 = int(input('Enter 2nd number Denominator: '))
    
    f1 = fractions.Fraction(num1, den1)
    f2 = fractions.Fraction(num2, den2)
    
    equ = str(input('Select Operation, +, * or /?: '))
    
    if equ == '*':
        result = f1 * f2
    elif equ == '/':
        result = f1 / f2
    elif equ == '+':
        result = f1 + f2
    
    whole = result.numerator // result.denominator
    remainder = result.numerator % result.denominator
    
    if whole != 0 and remainder != 0:
        print('{} {}/{} = {} {}/{}'.format(f1, f2, result.numerator, whole, remainder, result.denominator))
    elif whole != 0:
        print('{} {}/{} = {}'.format(f1, f2, result.numerator, whole))
    else:
        print('{} {}/{} = {}/{}'.format(f1, f2, result.numerator, remainder, result.denominator))
    

    In this code, I've added a section after the computation to extract the whole number and the remainder of the fraction. Then, I check the conditions to format the output correctly. If the whole number and remainder are both non-zero, I print the result in the format of "whole_number remainder/denominator." If only the whole number is non-zero, I print it as "whole_number." Otherwise, I print it as "remainder/denominator."

    Now the output should appear as you what you wanted!