Lecture 8 Flashcards
Function
Is a reusable block of code that can be executed on an as needed basis
What do we use functions for?
To help organize code
Make code more modular, and therefore scalable
Make debugging easier
Avoid repetition
Support code sharing
Function calling
A function is called when the program requests to run the code in the function, calling a function, interrupts the linear flow of a program the program will:
Jump to another place in the file
Execute the function code
Return back to the main part of the program where the function was called
Fuction syntax
def <function>(argument info):
<function></function></function>
<end>
<main>
<function name(arguments)>
</main></end>
Preliminary observations about functions
Function definitions must appear before function calls in the file
There can be multiple calls to the same function within a program
Arguments can be sent by value or as variables in function calls
Variables sent as arguments do not have to have the same name as the argument name in the function declaration
Default arguments
Arguments that have default values if they are admitted during a function call
Keyword arguments
Arguments referenced by name rather than position during function call
Preliminary observations about default/keyword arguments
Default arguments must appear at the end of the argument list in the function definition. Only default arguments can be omitted.
Keyword arguments must use the same argument name in the function call as the function definition. Only the last arguments in the argument list can be keyword arguments, though they can be provided in any order.
Functions have access to
- Arguments in the function definition
- variables defined within the function, local variables
- variables defined in the main program before the function call global variables
Functions can change
- argument values and local variables
- Global variables, but only when declared with the global keyword in the function
Arbitrary arguments
If the number of arguments being sent to a function is variable, use a* before the argument
Arbitrary keyword arguments
If the number of keyword arguments being sent to a function is variable use a ** before the argument name
Mixing arguments
The following order must be followed in both of the function, definition and function call
1) positional arguments
2) default arguments
3) keyword argument
4) arbitrary arguments
5) arbitrary keyword
Return
Return to the function to immediately return to the function that called it and return the value that is to the right of return