+ 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))
7 ответов
+ 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.
+ 7
You could try using eval(), like this:
operation = input()
print(eval(operation+'((a, b))'))
>>>
multiply
28
+ 4
I think that is because you can't call function as user input.
+ 2
@Nirjhar Kuba's change does what you are looking for.
@Kuba Thank you for teaching me a cool trick.
+ 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.
+ 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.
+ 1
Thanks @Milos