+ 2

def add(x, y): return x + y def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b)) i dont understand the func part like how is the code reading it, it wasnt definined for anything

5th Apr 2017, 9:48 PM
Seth T
5th Apr 2017, 10:04 PM
Ulisses Cruz
+ 7
Yes! arguments: parameters: a --> x b --> y add --> func
5th Apr 2017, 11:13 PM
Ulisses Cruz
+ 6
There is nothing special about the parameter called func. If you want you can change its name and it will still work: def do_twice(other, x, y): return other(other(x, y), other(x, y)) And there is nothing special about the place it was put. you can put it in the middle or at last and it will still work. def do_twice(x, y, func): return(func(x, y), func(x, y)) print(do_twice(a, b, add)) In Python you can pass a function as argument to another function. It is treated as another object.
5th Apr 2017, 11:10 PM
Ulisses Cruz
0
sorry man but this is just confusing. i understand everything i just need to further understand why func is there why is putting the word func specifically, in that spot, so important
5th Apr 2017, 11:01 PM
Seth T
0
does add correspond to func during print line and x,y correspond to a,b?
5th Apr 2017, 11:08 PM
Seth T
0
hell yea awesome thank vm
5th Apr 2017, 11:13 PM
Seth T
0
simply put, you can replace func with anything. func is passed as an argument to the function do_twice. It is denoted by func as it has to be a function in this case for it to work. For example, you could define a new function: def floor_divide(x, y): return x//y def divide_functions(viable_function, a, b): return viable_function(a, b)/viable_function(a, b) print(divide_functions(floor_divide, 17, 13)) here, viable_function = floor_divide(): this final call is exactly the same as: (floor_divide(17, 13))/(floor_divide(17, 13)) which equals (17//13)/(17//13) or 1/1 or, infact, 1. (I think)
9th Apr 2017, 6:52 PM
Callum Rogers