First code:
# -*- coding:gb2312 -*-
def test(a,b,funC):
result = funC(a,b)
return result
funC = eval(input("请输入函数"))
num = test(11,22,funC)
print(num)
You can enter anonymous functions like lambda x,y:x y in the input.
Now I think it is too troublesome to input lambda x, y: x y. I want to directly write the previous lambda x, y: section. When inputting, directly enter the It becomes as follows:
Second code:
# -*- coding:gb2312 -*-
def test(a,b,funC):
result = funC(a,b)
return result
funA = eval(input("请输入函数"))
funB = "lambda x,y:"
funC = eval(funB)+funC
num = test(11,22,funC)
print(num)
After changing , I ran the program:
The result is the following error.
I didn’t understand it at once, and I don’t know what it means.
I want to ask, why can’t I change it like this?
In the first piece of code:
funC = eval(input("请输入函数")) #运行时输入:lambda x,y:x+y
and the second code:
funA = eval(input("请输入函数")) #运行时输入:x+y
funB = "lambda x,y:"
funC = eval(funB)+funC
Shouldn’t these two pieces of code be equivalent?
Why can the former be executed smoothly but the latter will report an error?
The second code should be:
What you entered is not a function, not a function, not a function. What you entered is character shifting. The function of eval is to treat the string you input as a python code and execute it
Two points: