Python novice asked about anonymous functions
扔个三星炸死你
扔个三星炸死你 2017-06-13 09:24:43
0
3
969

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?

扔个三星炸死你
扔个三星炸死你

reply all(3)
刘奇

The second code should be:

strA = input("请输入函数")
strB = "lambda x,y:"
funC = eval(strB+strA)

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:

# -*- coding:gb2312 -*-
def test(a,b,funC):
    result = funC(a,b)
    return result

funA = input("请输入函数") #这儿改成 input("请输入函数")
funB = "lambda x,y:"
funC = eval(funB)+funC   #这儿改成 eval(funB+funA)
num = test(11,22,funC)
print(num)
phpcn_u1582
funC = eval("lambda x,y:" + input("请输入函数"))
num = test(11,22,funC)
print(num)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template