functions Flashcards
What is a function?
a reusable set of operations
Why use functions?
because functions are reusable and add simplicity to your program.
What are the components of a function?
keyword DEF used to define the function function NAME to call/refer to the function PARAMETERS represent the input data to pass into the function to be used to perform a meaningful task ARGUMENTS are the actual values passed into the function, represented by the parameters note: the position of parameters are important, as the arguments will be matched to the parameters based on their respective positioning note: if we call a function with less or more arguments than defined parameters, Python will throw an error keyword RETURN returns our output from the function and exits the function
Python best practice: define our functions first before beginning our main code to ensure that our functions can be used anywhere in the program safely
What is the function scope and data lifecycle in Python?
Scope is the extent to which the variable and data items inside a function are accessible in the program.
in Python, the scope of a function is the function’s body. Once the function ends, it returns to the outer scope
Data lifecycle refers to the fact that data created inside a function cannot be used outside a function unless it is returned from that function. Otherwise, the data will be released from memory and unrecoverable once the function ends.
What is lambda?
Lambda is an anonymous function that returns some form of data.
Lambda functions are defined used the LAMBDA keyword
Python best practice: since lambda functions return data, it’s best practice to assign lambda functions to a variable
syntax of a lambda function: lambda parameters: expression
what is an expression?
an operation that returns something
what is a limitation of lambda?
a lambda function’s expression must be single line
Why use lambda functions?
they work well as function arguments for other functions