Functions
Default arguments¶
We can add default arguments in a function to have default values for parameters that are unspecified in a function call:
Variable¶
check the code
This causes an UnboundLocalError, since Python doesn't allow functions to modify variables that are outside the function's scope. A better way would be to pass the variable as an argument and reassign it outside the function.
a better solution will be:
Lambda Expressions¶
You can use lambda expressions to create anonymous functions. These are functions that don’t have a name. They are helpful for creating quick functions that aren’t needed later in your code. This can be especially useful for higher order functions, or functions that take in other functions as arguments.
With a lambda expression, this function:
can be reduced to:
Components of a Lambda Function
- The
lambda
keyword is used to indicate that this is a lambda expression. - Following
lambda
are one or more arguments for the anonymous function separated by commas, followed by a colon:
. Similar to functions, the way the arguments are named in a lambda expression is arbitrary. - Last is an expression that is evaluated and returned in this function. This is a lot like an expression you might see as a return statement in a function.
map()
is a higher-order built-in function that takes a function and iterable as inputs, and returns an iterator that applies the function to each element of the iterable.
in this case maps()
is getting the value of numbers (an iterable variable) and use it in the lambda
expression, it will get the values in numbers
and will get the average.
filter()
is a higher-order built-in function that takes a function and iterable as inputs and returns an iterator with the elements from the iterable for which the function returns True, here and example: