+ 1
Why am having error in this code? Its saying something like- str is not callable..
The code is--- cal=input("Enter add for add, subtract to subtract, multiply to multiply, divide to divide two numbers.. ") x=int(input("Enter 1st number: ")) y=int(input("Enter 2nd Number: ")) def add(x,y): return x+y def subtract(x,y): return x-y def divide(x,y): return x/y def multiply(x,y): return x*y def calculate(cal,x,y): return cal(x,y) print(calculate(cal,x,y))
8 Réponses
+ 7
#Fixed code following @Álvaro answer:
cal=input("Enter add for add, subtract to subtract, multiply to multiply, divide to divide two numbers.. ")
# if using Python ligther than version 3, you need to use 'raw_input()' instead of 'input()' to get user entry as string:
#cal=raw_input("Enter add for add, subtract to subtract, multiply to multiply, divide to divide two numbers.. ")
x=int(input("Enter 1st number: "))
y=int(input("Enter 2nd Number: "))
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def divide(x,y):
return x/y
def multiply(x,y):
return x*y
def calculate(cal,x,y):
return mymap[cal](x,y)
mymap = {'add':add, 'subtract':subtract, 'multiply':multiply, 'divide':divide}
print(calculate(cal,x,y))
+ 4
cal only stores a string, not a function, so it's not callable. Please consider mapping your function names to values (actual functions) in a dictionary:
mymap = {'add':add, 'subtract':subtract, 'multiply':multiply, 'divide':divide}
and use
mymap[cal](x, y)
(adapted from https://stackoverflow.com/questions/4246000/how-to-call-JUMP_LINK__&&__python__&&__JUMP_LINK-functions-dynamically )
+ 2
code is correct
there is no error in the code
+ 2
It's just Álvaro said. For example, user wants to use and enters 'add'. Then the variable 'cal' is string 'add'. This is not a function, so at 'def calculate(cal,x,y)' part, you can't use string 'add' as a function 'add'. So do it just Álvaro suggested. That's the solution.
+ 1
input() gives string, but at defining calculate, you are using string cal as if it is function. So the error occurs. You should use if statement and call in code, not with string you got with input.
0
I know But why the error Occurs?
0
when I reach Map function I will Try
0
orb_H how its Done in this code? Can u plz explain