Can decimal module process unknown values?

Viewed 48

I am a novice to the decimal module and I am not sure if the decimal module can read and process unknown values. What can I change for the code to make it work?

I researched on it, however, I cannot find an ideal answer

    from decimal import Decimal

    def Addition(x,y):
        sum=Decimal('x')+Decimal('y')   
        print("The sum of {0} and {1} is {2}".format(x, y,sum))

    x=float(input("Enter your first  number: "))
    print("Your first number is="+str(x))
    y=float(input("Enter your second  number: "))
    print("Your second number is="+str(y))

    Addition(x,y)

I expected an addition of x and y, but the output is an invalid operation of [<class 'decimal.ConversionSyntax'>]

2 Answers

See comments in code.

from decimal import Decimal

def Addition(x,y):
    sum=x+y   #You don't need quotes around x and y
    print("The sum of {0} and {1} is {2}".format(x, y,sum))

x=Decimal(input("Enter your first  number: "))
print("Your first number is {}".format(x)) #No need to convert to string
y=Decimal(input("Enter your second  number: "))
print("Your second number is {}".format(y)) #No need to convert to string

Addition(x,y)

Output:

Enter your first  number: 5.789
Your first number is 5.789
Enter your second  number: 5.34566
Your second number is 5.34566
The sum of 5.789 and 5.34566 is 11.13466

IIUC you meant:

from decimal import Decimal
def Addition(x,y):
    sum=Decimal(x)+Decimal(y)   
    print("The sum of {0} and {1} is {2}".format(x, y,sum))
    x=float(input("Enter your first  number: "))
    print("Your first number is="+str(x))
    y=float(input("Enter your second  number: "))
    print("Your second number is="+str(y))
Addition(x,y)
Related