Skip to content Skip to sidebar Skip to footer

Addition Function In Python Is Not Working As Expected

I tried to create a function using which I want to do mathematical operations like (Addition and Multiplication), I could able to prompt the values and when I insert the values res

Solution 1:

You don't need the functions nor the sum or multiply variables, just put the operation in str.format(), and you were missing the last position.

# def addition(num1,num2):  #     return num1+num2# def multiplication(num1,num2):#     return num1*num2print("1.addition")
print("2.multiplication") 
choice = int(input("Enter Choice 1/2"))

num1 = float(input("Enter First Number:"))
num2 = float(input("Enter Second Number:"))
# sum = float(num1)+float(num2)# multiply = float(num1)*float(num2) if choice == 1: 
    print("additon of {0} and {1} is {2}".format(num1,num2, num1 + num2))
elif choice == 2:
    print("additon of {0} and {1} is {2}".format(num1, num2, num1 * num2))

And know that you can use fstrings (>= Python 3.6):

if choice == 1:
   print(f"additon of {num1} and {num2} is {num1 + num2}")
elif choice == 2:
   print(f"additon of {num1} and {num2} is {num1 * num2}")

Old-style formatting:

if choice == 1:
   print("additon of %s and %s is %s" % (num1,num2, num1 + num2))
elif choice == 2:
   print("additon of %s and %s is %s" % (num1, num2, num1 * num2))

Or string concatenation:

if choice == 1:
   print("additon of " + num1 + " and " + num2 + " is " + (num1 + num2))
elif choice == 2:
   print("additon of " + num1 + " and " + num2 + " is " + (num1 * num2))

Each person does it a different way and it's useful to know all of them sometimes.

Solution 2:

You're missing the positional specifier for the result. Since you have three arguments, you need to specify three positions.

print("additon of {0} and {1} is {2}".format(num1,num2, sum))

Post a Comment for "Addition Function In Python Is Not Working As Expected"