0

Python Higher Order Functions

Hi, I am new to Python and am currently learning Chapter 05 of the Python lesson. I have a query on higher order function. Please refer to below for my code. x = int(input()) print("Input a number:",x) print("Your number will produce the output of double adding five:") def Higher(func, arg): return func(func(arg)) def Base(x): answer = int(x+5) return answer print(Higher(Base,x)) 01. I understand that the above will not work if I try to code 2 inputs because the Base function will return only 1 value to the Higher function. Is this understanding correct? 02: How should I code if I want to use higher order function with 2 arguments (eg. x + y + 5 twice) ? 03. Is this a correct use case to use higher order function? Thank you in advance.

22nd Mar 2020, 4:20 AM
Aron
2 Respostas
+ 1
First, your understanding appears to be correct. Second, I attached code below that takes two inputs, adds them together, adds five, doubles that sum and then adds five again (I think that was what you were asking for): x = int(input()) y = int(input()) print("Input a number:",x) print("Input another number:",y) print("Your number will produce the output of adding both inputs, adding five, and then doubling the result and adding five again:") def Higher(func, arg1, arg2): return func(func(arg1,arg2), func(arg1,arg2)) def Base(x, y): answer = int(x+y+5) return answer print(Higher(Base,x,y)) I really hope this helps!
22nd Mar 2020, 4:44 AM
Eden
+ 1
Hi Eden, Thank you so much. I got it after your explanation. # return func(func(arg1,arg2), func(arg1,arg2)) This was the code that I failed to write in my script which causes errors when I try to run it. Your explanation also helps me on my understanding for Decorators, which is basically similar to the above. Thank you and appreciate your kind assistance in this.
22nd Mar 2020, 5:06 AM
Aron