
|
Lesson 6 Notes: Home-Made Functions
- What is a function again?
- Function = defined set of instructions
- Often stored in sets called modules
- May or may not take arguments
- May or may not return values to program
- Function Recipe:
- Define the function
- Give it a name
- Create directions for function to follow
- Later in program, call your function
- Setting Up A Function
def name(arguments):
Commands
- def = required word, lowercase
- name = You make up
- (arguments) = initialize variables for function
- : = Required at end of line
- Commands = Must be indented to identify it as part of the function.
- Example
# Define the function
def my_function():
print “I love school”
#Use function
my_function()
- Program Flow
- Functions may be defined at any point in the program before the function itself is called.
- Functions are run when called.
- Feeding Your Function
- To send values to your functions, create a variable name in the definition
def my_function(name, name2):
print name+name2
- The variable name only works inside the function (it is a local variable)
- The function can use only local variables.
- Pass the Values, Please
- To send values to the function, place the values in the function call
def my_function(name, name2):
print name+name2
my_function (“Bob”, “White”)
- Value types must match those expected by the function.
- Functions can take variables or other functions as arguments.
- Review
- How do you create a function?
- How do you send values to a function for processing?
- What is a “local variable”?
- Why would reading a program from start to finish not help you understand what happens in the program?
Restricted access |