Help needed in Using Python Functions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help needed in Using Python Functions

I am getting an error on line "print(operation(a, b))" as TypeError: 'str' object is not callable even when the input is either multiply or minus, however if i comment the above code and un-comment the commented code i get the desired results: 28 and -3 def multiply(x, y): return x * y def minus(x, y): return x - y a = 4 b = 7 operation = input() print (operation) print(operation(a, b)) #operation = multiply #print(operation(a, b)) #operation = minus #print(operation(a, b))

16th Dec 2017, 11:17 AM
Nirjhar Vats
Nirjhar Vats - avatar
7 Answers
+ 8
input() returns a string and you can't call a string. In your positive example you are assigning multiply, which is a function, to operation variable. And so, operation becomes a function, too, not a string.
16th Dec 2017, 12:30 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 7
You could try using eval(), like this: operation = input() print(eval(operation+'((a, b))')) >>> multiply 28
16th Dec 2017, 11:28 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
I think that is because you can't call function as user input.
16th Dec 2017, 11:21 AM
Vukan
Vukan - avatar
+ 2
@Nirjhar Kuba's change does what you are looking for. @Kuba Thank you for teaching me a cool trick.
16th Dec 2017, 11:43 AM
John Wells
John Wells - avatar
+ 2
In first case your variable operation is string. In the section that works fine your variable is function. You can try to use built-in function type(operation) in both cases and you will understand. eval() function basically transforms string into executable code.
17th Dec 2017, 1:38 AM
Milos Nikic
Milos Nikic - avatar
+ 1
Thanks Kuba.... the eval function did the desired work: operation = input() print(eval(operation+'(a, b)')) however my question still persist that why does the same Print functioncall gives error and taking input from user? #This code gives error operation = input() print (operation) #user input is multiply print(operation(a, b)) #giver error #This code works fine operation = multiply print(operation(a, b)) may be i am missing out some concept.
16th Dec 2017, 11:53 AM
Nirjhar Vats
Nirjhar Vats - avatar
+ 1
Thanks @Milos
17th Dec 2017, 4:12 AM
Nirjhar Vats
Nirjhar Vats - avatar