Aug-30-2021, 07:08 AM
1. Well, yes, of course, just call the functions on line 21 so that their return values are passed to
2. When you use the function name without parentheses, that refers to the function itself. It does not call the function. Being able to pass functions around to other functions is very useful. For example, when you want to do something when a button is pressed on a UI, you express the "something" as a function, but you don't call it - you give that function to the library code that handles the button press. It's again, all about parameterising the thing to be done. Other examples are when you want to operate on collections, e.g.
- doing the same thing to every item in a collection:
calculate_result
2. When you use the function name without parentheses, that refers to the function itself. It does not call the function. Being able to pass functions around to other functions is very useful. For example, when you want to do something when a button is pressed on a UI, you express the "something" as a function, but you don't call it - you give that function to the library code that handles the button press. It's again, all about parameterising the thing to be done. Other examples are when you want to operate on collections, e.g.
- doing the same thing to every item in a collection:
def square(x): return x ** 2 values = [1, 2, 3] squared_values = map(square, values)
names = ["alice", "bob", "mary"] capitalised_names = map(lambda name: name.title(), names)- keeping items in a collection that satisfy a condition
def even(x): return x % 2 == 0 values = [3, 2, 4, 7, 20, 16] evens_only = filter(even, values)
names = ["Alice", "Mary", "Bob", "Andrew"] names_starting_with_a_only = filter(lambda name: name.startswith("A"), names)