Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help!!!! Error in Code
#1
Hi,

I am working on a calculator.

I somehow completed it, but i am getting an error.
Unable to figure out.

Help!

Thanks!

# Add
def add (n1, n2):
    return n1 + n2 

# substract
def subtract(n1, n2):
    return n1 - n2 

# multiply
def multiply (n1, n2):
    return n1 * n2 

# divide
def divide (n1, n2):
    return n1 / n2

operations = {"+" : "add",
         "-" : "subtract",
         "*" : "multiply",
         "/" : "divide"
         }


num1 = int(input("What's the first number?"))
for operation in operations:
    print(operation)
sign = input("What do you want to do?")
num2 = int(input("What's the new number?"))

calculation_function = operations[sign]
Answer = calculation_function (num1, num2)
print (f"{num1}{sign}{num2} = {Answer}")
Error:
Answer = calculation_function (num1, num2) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'str' object is not callable [error]
[/error]
Reply
#2
Put the function names in only, without any quotes or brackets:

operations = {"+" : add,
             "-" : subtract,
             "*" : multiply,
             "/" : divide
             }
Then

Answer = operations[sign](num1, num2)
There may be other ways to do this!
Ravi1001 likes this post
Reply
#3
Thanks!!

worked like a charm!


(May-13-2024, 12:39 PM)Ravi1001 Wrote: Hi,

I am working on a calculator.

I somehow completed it, but i am getting an error.
Unable to figure out.

Help!

Thanks!

# Add
def add (n1, n2):
    return n1 + n2 

# substract
def subtract(n1, n2):
    return n1 - n2 

# multiply
def multiply (n1, n2):
    return n1 * n2 

# divide
def divide (n1, n2):
    return n1 / n2

operations = {"+" : "add",
         "-" : "subtract",
         "*" : "multiply",
         "/" : "divide"
         }


num1 = int(input("What's the first number?"))
for operation in operations:
    print(operation)
sign = input("What do you want to do?")
num2 = int(input("What's the new number?"))

calculation_function = operations[sign]
Answer = calculation_function (num1, num2)
print (f"{num1}{sign}{num2} = {Answer}")
Error:
Answer = calculation_function (num1, num2) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'str' object is not callable [error]
[/error]
Reply
#4
Did it work? Well actually you cannot call a string function in Python. You must assign a value to it. x = " " " What do you want to do?" " " # This now becomes a type string data. So rewrite it again.
Programs are like instructions or rules. Learning it gets us closer to a solution. Desired outcome. Computer talk.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020