In this module we will review the Void function.  We will also look at both local and global variables and in this module we will be covering Lists.  We will look at how to create a list, finding items in a list to process, examine the various list methods and built-in functions, and how to process lists.

.

Functions

A function is a group of statements that exist that we can use in a program for the purpose of performing a specific task.  We call this modular programming.  Dividing up code into sections that can be executed as needed.  We can also "store" these sections of code to be reused in other programs.

Void Functions and Value-returning functions

A void function simply executes the statements is contains and then terminates.  A value-returning function executes the statement that it contains, then returns a value back to the statement of the original program that "called" the function.  The input function is a value-returning function.  It get the data that the user types on the keyboard and returns that data as a string to the program.

The code for a function is known as a function definition.  To execute the function, you write a statement that calls it - such as input.

You name your own functions (except for PYTHON defined functions already created).

1.  you can't use one of Python's keywords

2.  a function name cannot contain spaces

3.  the first letter must be A-Z, a-z or underscore

4.  after the first charter must use A-Z, a-z, underscore, 0-9

5.  uppercase and lowercase are different

Defining a function and calling it

When creating a new function the SYNTAX is:

def function_name():

     statement

     statement

     etc.

The first line is the function header.  The "statements" are the block that are code for that function.  You MUST indent the statements in the block in PYTHON>

When we want to "call" a function - have it executed from our program we:

function_name()

Hierarchy Charts

One of the ways we can visualize the relationships between our programs and any functions that they "use" can be done through a hierarchy chart - also called a structure chart.   This type of chart uses rectangles to represent all of the functions that may be "used - called" from our main program.

Local Variables

One of the very IMPORTANT things about using functions is to understand two terms - Local Variables and Global Variables.  With local variables - these are created inside a function and CANNOT be accessed by statements that are outside of the function.  Different functions CAN have the same variable names because functions cannot see each other's local variables.

Anytime you assign a value to a variable inside of a function you have created the local variable. 

Scope

A variable's scope is the part of a program where the variable may be accessed.  A variable is only visible (can be used and recognized) by statements within the variable's scope.

Passing Arguments to Functions

An argument is any piece of data that is passed into a function when that function is called (remember to call a function means we want to have that particular function executed).  A parameter is a variable that receives an argument that is passed into the function.

The main program has the ARGUMENT (local variable name with data) and the function has the PARAMETER (local variable name) where the data will be sent (it's like an assignment statement).  Once the function has the data inside of the parameter (local variable) it can use it in the function.  Page 182 of your textbook gives an excellent example of how this works.

You CAN pass multiple arguments (more than one piece of data) to a function to be used.  Both the main program (calling program) and the function (called program) MUST have the same number and data types of the arguments and parameters being used.  Page 185-186 shows this example.

You may also pass keyword arguments to functions where parameter_name=value  You can see this example on pages 189-190.

Global Variables

Global variables are accessible to ALL the function listed in a program.  When you begin a program - BEFORE defining the main() program, you can create and assign your Global variables.  These are ALWAYS done before the definition of any of your programs or functions.  Then EACH part of the program - main and functions can use the Global variable as defined.

HOWEVER - these Global variables can be dangerous to use.  It is recommended wherever possible to only use local variables.  However - you can create a Global constant variable whose value doesn't change through the program and functions.  This will avoid any other other problems with global variables.

Value-Returning Functions

The functions we have looked at before were only those where the main() program called the function and the function performed some action before returning back to the main program.  We have certain types of functions where we want to "pass back" calculated values back to the main() program.  We use the RETURN statement to return a value back to the main().  You can return multiple values as well.

PYTHON uses a standard library of functions that have already been written for you.  You just need to become familiar with these various functions and use them as needed.  These are called LIBRARY FUNCTIONS.

Some of the library functions deal with random numbers which can be very useful for many programs.  Some of these are randint, randrange, random, and uniform.

Random numbers need to be generated with a "seed" value - this value is used in a calculation to generate the random number.

Storing user defined functions in a Module

As programs get larger and larger, it might be wise to actually store several functions together into a Module and then use the module.function to use what you need in your program.  This is called modular programming.

Menu-Driven Programs

A men-driven program displays a list of operations on the screen, and allows the user to select the operation that they want to be performed.  The list displayed on the screen is called a menu.  you can choose the operation by using an if-elif-else statement.

Sequence

A sequence is an object that holds multiple items of data, stored one after the other.  You can perform operations on a sequence to examine and manipulate the items stored in it.

Lists

A list is an object that contains multiple data items.  They are "mutable" - which means their contents can be changed during a program's execution.  These are dynamic data structures.  Each item in the list is called an "element".  All of the elements in the list can have different data types.  We reference things in the list by their position in the list.

     even_numbers = [2, 4, 6, 8]

     info = ['Alicia', 27, 17.25]

     names = ['Mary', 'John', 'Phil', 'Joe']

There is a built in 'list' function as well:

     numbers = list(range(5))   calls the range function with '5' as the argument and returns s list [0, 1, 2, 3, 4]

Repetition Operator

     list * n        list is your list and n is the number of copies to make

     numbers = [0] * 5

     print(numbers)

     [0, 0, 0, 0, 0]

Iterating over a List with for Loop

Iterating (repeating a number of times) can be done with a list also using the for loop:

     numbers = [99, 100, 101, 102]

     for n in numbers:

           print (n)

This will produce: 

99

100

101

102

Indexing a List

We can also use an index to access individual elements of the list.  The index is the specific position in the list.  The index MUST start with 0 as it's position

     my_list = [10, 20, 30, 40]

     print(my_list[0], my_list[1], my_list[2], my_list[3]

or

     index = 0

     while index < 4

          print(my_list[index])

          index += 1

You can also use negative indexes - BUT remember index [-1] is the LAST element of the list.

The len Function

This built in function returns the length of a sequence (how many elements in the list).

Remember - we can change values in the list that has already been created with data - Mutable!

Concatenating Lists

To concatenate means to join two things together.  We use the + operator to concatenate two lists.

List Slicing

Slicing expression selects a range of elements from a sequence in the list.

     list_name[start : end]       *****important - the "end" value is NOT included in the

The in Operator

This allows you to search for an item in the list.

     item  in  list

Methods and built-in Functions

append(item)
Method is commonly used to add items to a list.

index(item)

Returns the index of the first element whose value is equal to item.

 insert (index, item)

Inserts item into the list at the specified index

sort()

Sorts the items in he list so they appear in ascending order (lowest to highest)

remove (item)

removes the first occurrence of the item from the list (the item value must exist in the list to remove)

reverse()

reverses the order of the items in the list

del my_list[2]

deletes the element at the index location

min and max functions

min will accept a list as an argument and returns the item that has the lowest value.

max will accept a list as an argument and returns the items that has the highest value.

Copying a List

To make a copy o f a list, you must copy the list's elements.  Depending on your code - you might have two lists with different names - but actually point to the same memory location.  You might also have two lists with different names that point to separate memory locations, but have the exact same data.

Processing Lists

Some common ways to process lists include: 1) total the values in a list; average the values in a list

Passing a List as an argument to a Function

There are built in functions that accept a complete list as an argument into the function.  You can also return a list from a function.

Lists and Files

You can use a list to store the data that will be written out to a file.

2-Dimensional Lists

This type of list has other lists as its elements (rows and columns).  When we have 2-dimensional lists we MUST have two indexes - one for the column position and one for the row position.

Tuple

A tuple is an immutable sequence - its contents CANNOT be changed.  We have the built in list function to convert a tuple to a list, and the built-in tuple function to convert a list to a tuple.