Functions as Arguments

preview_player
Показать описание
MIT 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016
Instructor: Dr. Ana Bell

This in-class question demonstrates how functions can be used as arguments in other functions in Python.

License: Creative Commons BY-NC-SA
Рекомендации по теме
Комментарии
Автор

How did the program binded func(x) to f(x), that really got me confused ):

emiliobazan
Автор

I don't fully grasp it. I've written the code below.

def sq(func, x):
y = x**2
return func(y)

def f(x):
return x**2

calc = sq(f, 2)
print(calc)

And I get that if you follow the steps with sq(f, 2).
You get the following:
func = f (because func = f)

y = 2**2 (because x = 2)
y = 4
return func(4)

But now func(y) = f(x). Since func(4), f is also f(4), which means that 4**2 = 16

The part where func(y) suddenly becomes f(x) is pretty confusing though.

onee
Автор

a little bit confusing function but I figured out by writing it on paper! Thank you MIT and professor Bell!

waynezhou
Автор

Does this help anyone?



def square(pass_in_function, x1):
y1 = x1**2
# pass_in_function = another_square -> from main program call
# you could actually say the return is "return another_square(y1)"
return pass_in_function(y1)

def another_square(x2):
#this is being called by "pass_in_function" inside of function "square"
return x2**2

calc = square(another_square, 2)
print(calc)

williamkoch
Автор

The get the answer for calc = sq(f, 2), pass the argument (f, 2) to function sq(func, x) which equal to y = x**2, it means that the "x" value multiply by itself by 2 times.
The value of "f" is equal to function f(x), return x**2, which mean 2x2 = 4.
Put the answer 4 back to function sq(func, x), y=x**2 or y=4*4 = 16.

AllGroundsCoffee
Автор

hey there! how can i get in to MIT? i really excited to be and learn there (00)

KIRILLINGUSS
Автор

I thought we will get error because in the definition we did not put the brackets
def sq(func(), x) we put func not func()

peasant
Автор

It's more like a nursery school than MIT! So simple.

RameenFallschirmjager