Transcript Chapter 6

Guide to Programming with
Python
Chapter Six
Functions: The Tic-Tac-Toe Game
What Do You See?
Sierpinski Square
(produced by SierpinskiSquare.py)
Escher Circle limit IV
http://www.dartmouth.edu/~matc/math5.pattern/lesson7math.html
Guide to Programming with Python
2
Objectives
 Understand why/when/how to use functions
 Write your own functions
 Accept values into your functions through
parameters
 Return information from your functions through
return values
 Work with global variables and constants
 Create a computer opponent that plays a strategy
game
Guide to Programming with Python
3
Reasons to Use Functions
 Divide and conquer: divide complicated tasks into
simpler and more manageable tasks.
 Avoid writing redundant program code (many
programs require that a specific function is
repeated many times)
 Enhance the readability of codes (a code can be
broken up into manageable chunks; easy to follow
the flow of the program)
 Testing and correcting errors is easy because
errors are localized and corrected
 A single function written in a program can also be
used in other programs also (software reuse)
Guide to Programming with Python
4
Breakdown of the Tic-Tac-Toe Game
display the game instructions #define a function to enhance readability
determine who goes first
create an empty tic-tac-toe board
display the board #define a function to avoid repeating the codes
while nobody’s won and it’s not a tie
if it’s the human’s turn
get the human’s move
update the board with the move
otherwise
calculate the computer’s move
update the board with the move
display the board
switch turns
congratulate the winner or declare a tie
Guide to Programming with Python
5
User-defined Functions
def instructions():
"""Display game instructions."""
print "Welcome to the world's greatest game!"
 Functions make programs easier to read, write and
maintain
 Function definition: Code that defines what a new
function does
 Function header: First line of a function definition
 Give function name that conveys what it does or
produces
Guide to Programming with Python
6
Documenting a Function
def instructions():
"""Display game instructions."""
print "Welcome to the world's greatest game!"
 Docstring: String that documents a function
 Docstrings
–
–
–
–
Triple-quoted strings
Must be the first line in your function
Not required, but a good idea
Pop up as interactive documentation in IDLE
Guide to Programming with Python
7
Calling a Function
instructions()
 Call tells the computer to execute function
instructions()
 Call works just like call to built-in function
 Tells the computer to execute previously-defined
function
Guide to Programming with Python
8
Abstraction
 Abstraction: Mechanism that lets you think about
the big picture without worrying about the details
 Functions facilitate abstraction
 Can call function instructions() without worrying
about the details
Guide to Programming with Python
9
Encapsulation
 Encapsulation: A technique of keeping
independent code separate by hiding the details
 Variables created in a function cannot be directly
accessed outside the function
 Parameters and return values allow for
information exchange
–
–
–
–
Functions with no arguments and no return values.
Functions with arguments and no return values.
Functions with no arguments and return values
Functions with arguments and return values
Guide to Programming with Python
10
Receiving Information through Parameters
def display(message):
print message
 Parameter: A variable name inside the parentheses of
a function header that can receive a value
 Argument: A value passed to a parameter
 Parameters must get values; otherwise, error
 Multiple parameters can be listed, separated by
commas
 Sample call: display("Here’s a message for you.")
 Wonder if and how you can pass parameters to your
program?
– using sys module
11
Returning Information through Return Values
def give_me_five():
five = 5
return five
 Return value: A value returned by a function
 return statement returns values from a function
 return statement ends function call
 Can return more than one value from a function -list all the values in return statement, separated by
commas
 Sample call: number = give_me_five()
Guide to Programming with Python
12
Receiving and Returning Values
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response




Receives one value and returns another
Receives a value through its parameter question
Returns a value (either "y" or "n") through response
Sample call: answer = ask_yes_no("Enter y or n: ")
Guide to Programming with Python
13
Positional Parameters & Positional
versus Keyword Arguments
def birthday(name, age):
print "Happy birthday,", name, "!", "You’re", age
birthday("Jackson", 1)
Positional arguments: Arguments
birthday(1, "Jackson”)
passed to the parameters in order
birthday(name = "Jackson", age = 1)
birthday(age = 1, name = "Jackson")
Keyword argument: Argument passed to a specific
parameter using the parameter name
The biggest benefit of using keyword arguments is clarity.
#using default parameter value
def birthday(name = "Jackson", age = 1):
print "Happy birthday,", name, "!", "You’re", age
birthday("Mike", 10)
birthday(age = 10, name = "Mike")
birthday(name = "Mike")
Guide to Programming with Python
14
Positional or Keyword? (None or All)
 Once you use a keyword argument, all the remaining
arguments in the same function must be keyword arguments.
birthday(name = "Mike", 10)
#SyntaxError: non-keyword arg after keyword arg
 Try not to mix functions with positional arguments, and
functions with keyword arguments in your program (though you
can do it)
birthday("Mike", 1)
birthday(name = "Jackson", age = 10)
 Once you assign a default value to a parameter in the list, you
have to assign default values to all the parameters listed after it.
def birthday(name = "Mike", age)
#SyntaxError: non-default argument follows default argument
def birthday(name, age=1)
#Syntax Fine; but confusing, try not to use it
15
Global versus Local Scopes
 Scopes: Different areas of a program that are
separate from each other
 Every function has its own scope
 Functions can't directly access each other's
variables
 But can exchange information through
parameters and return values
Guide to Programming with Python
16
Global versus Local Variables
def func1():
local_name1 = "Func1” #local variable
print local_name1, global_name
#but access global_name but not local_name2
def func2():
local_name2 = "Func2"
print local_name2, global_name
#but can not access local_name1 here
global_name = "Global” #global variable
#can not access local_name1 & local_name2 here
func1()
func2()
Guide to Programming with Python
17
Shadowing/Changing a Global
Variable from Inside a Function
def demo():
global value1 #full access of global variable value1
value1 = -value1
value2 = -20 #a new variable with same name (shadow)
print "Inside local scope:", value1, value2, value3
value1 = 10
value2 = 20
value3 = 30
print "In the global scope:", value1, value2, value3
demo() # value1 is changed; value2 and value3 not
print "Back in the global scope", value1, value2, value3
 Shadow: To hide a global variable inside a scope by creating a
new local variable of the same name
 Not a good idea to shadow a global variable
Guide to Programming with Python
18
Understanding When to Use Global
Variables and Constants
 Use of global variables can lead to confusion
 Limit use of global variables
 Global constant: Global variable treated as a
constant
 Use of global constants can make programs
clearer
Guide to Programming with Python
19
Tic-Tac-Toe Pseudocode
display the game instructions #define a function to enhance readability
determine who goes first
create an empty tic-tac-toe board
display the board #define a function to avoid repeating the codes
while nobody’s won and it’s not a tie
if it’s the human’s turn
get the human’s move
update the board with the move
otherwise
calculate the computer’s move
update the board with the move
display the board
switch turns
congratulate the winner or declare a tie
Guide to Programming with Python
20
Representing the Tic-Tac-Toe Data
 Use a single list of 9 elements to represent the
board
 List elements will be strings, one character long
– Empty will be " "
– X will be "X"
– O will be "O"
Guide to Programming with Python
21
Tic-Tac-Toe Functions
Table 6.1: Tic-Tac-Toe Functions
Planned functions for the Tic-Tac-Toe game
Guide to Programming with Python
22
Summary
 What you need to know about functions
– Using keyword def to define a function
– Function header: The line that defines the function
– Docstring: a triple-quoted string that immediately follows a
function header and that documents what the function does
– Parameter: a variable/name in a function header that can
receive a value
– Argument: a value used in a function call that’s passed to a
parameter
– Keyword argument: an argument passed to a specific
parameter of a function by using its parameter name
– Default parameter value: the value in the function header
– Return value: a value returned by a function
Guide to Programming with Python
23
Summary (continued)
 Abstraction: a mechanism that lets you think about the big
picture without worrying about the details (think functions)
 Encapsulation: a principle of abstraction; a technique of keeping
independent code separate by hiding or encapsulating the details
(and it is the reason that we use parameters and return values)
 Variables and parameters created in a function can NOT be
directly accessed outside the function?
 Scopes: different areas of a program that are separate from
each other (global scope versus local scope)
 Global/local variable: a variable created in the global/local
scope (global variables can be accessed in any part of a program,
but local variables can not be accessed outside of its scope)
 You should avoid using global variables (but global
constants are good; variable name in capital letters)
Guide to Programming with Python
24