Home > Mobile >  Fraction in python
Fraction in python

Time:08-24

Context: I was making a calculator and decided to add a feature to calculate fractions but I kept getting the error below when I try to add fractions.

Code:

from fractions import Fraction

print("Enter 1 for Addition")
print("Enter 2 for Subtraction")
print("Enter 3 for Multiplication")
print("Enter 4 for Division")
print("Enter 5 for Adding Fractions")
print("Enter 6 for Subtracting Fractions")
print("Enter 7 for Multiplying Fractions")
print("Enter 8 for Dividing Fractions")

choice = input("Enter your choice : ")

if choice == "1":
  num1 = float(input("Enter number 1 : "))
  num2 = float(input("Enter number 2 : "))
elif choice == "2":
  num1 = float(input("Enter number 1 : "))
  num2 = float(input("Enter number 2 : "))
elif choice == "3":
  num1 = float(input("Enter number 1 : "))
  num2 = float(input("Enter number 2 : "))
elif choice == "4":
  num1 = float(input("Enter number 1 : "))
  num2 = float(input("Enter number 2 : "))

else:
  numerator = input("Enter numerator here : ")
  denominator = input("Enter denominator here : ")
  numerator2 = input("Enter numerator2 here : ")
  denominator2 = input("Enter denominator2 here : ")
  fraction1 = Fraction((numerator, denominator))
  fraction2 = Fraction((numerator2, denominator2))

if choice == "1":
  print(num1, " ", num2, "=", (num1   num2))
elif choice == "2":
  print(num1, "-", num2, "=", (num1 - num2))
elif choice == "3":
  print(num1, "x", num2, "=", (num1 * num2))
elif choice == "4":
  if num2 == 0.0:
    print("Unable to divde by zero")
  print(num1, "/", num2, "=", (num1 / num2))
elif choice == "5":
  print(fraction1, " ", fraction2, "=", (fraction1     fraction2))

else:
  print("Invalid choice")

I keep getting this error:

Traceback (most recent call last):
  File "main.py", line 32, in <module>
    fraction1 = Fraction(("a/b", "c/d"))
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/fractions.py", line 161, in __new__
    raise TypeError("argument should be a string "
TypeError: argument should be a string or a Rational instance

Also, I was programming in repl.it

CodePudding user response:

You're sending a tuple instead of numbers.Rational intances (https://docs.python.org/3/library/numbers.html#numbers.Rational).

This worked, although converting to int may not be what you really desire.

fraction1 = Fraction(int(numerator), int(denominator))
fraction2 = Fraction(int(numerator2), int(denominator2))
  • Related