+ 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))

4th Jun 2017, 8:55 AM
Kuldip Sharma
Kuldip Sharma - avatar
8 odpowiedzi
+ 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))
4th Jun 2017, 11:50 AM
visph
visph - avatar
+ 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 )
4th Jun 2017, 9:44 AM
Álvaro
+ 2
code is correct there is no error in the code
4th Jun 2017, 9:14 AM
Mayur Chaudhari
Mayur Chaudhari - avatar
+ 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.
4th Jun 2017, 11:49 AM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 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.
4th Jun 2017, 9:46 AM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
0
I know But why the error Occurs?
4th Jun 2017, 9:16 AM
Kuldip Sharma
Kuldip Sharma - avatar
0
when I reach Map function I will Try
4th Jun 2017, 9:46 AM
Kuldip Sharma
Kuldip Sharma - avatar
0
orb_H how its Done in this code? Can u plz explain
4th Jun 2017, 10:56 AM
Kuldip Sharma
Kuldip Sharma - avatar