search

Home  >  Q&A  >  body text

Python novice asked about anonymous functions

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?

扔个三星炸死你扔个三星炸死你2808 days ago1002

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-06-13 09:26:43

    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

    reply
    0
  • 滿天的星座

    滿天的星座2017-06-13 09:26:43

    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)

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-13 09:26:43

    funC = eval("lambda x,y:" + input("请输入函数"))
    num = test(11,22,funC)
    print(num)

    reply
    0
  • Cancelreply