Guide to Programming with Python

Post on 19-Mar-2016

30 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

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. Objectives. Understand why/when/how to use functions - PowerPoint PPT Presentation

Transcript

Guide to Programming with Python

Chapter SixFunctions: The Tic-Tac-Toe Game

What Do You See?

Guide to Programming with Python 2

Escher Circle limit IVhttp://www.dartmouth.edu/~matc/math5.pattern/lesson7math.html

Sierpinski Square (produced by SierpinskiSquare.py)

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 Gamedisplay the game instructionsdetermine who goes firstcreate an empty tic-tac-toe boarddisplay the boardwhile 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 turnscongratulate the winner or declare a tie

Guide to Programming with Python 5

#define a function to avoid repeating the codes

#define a function to enhance readability

User-defined Functionsdef 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 Functiondef 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 Functioninstructions()

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 Parametersdef 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 Valuesdef 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 Valuesdef 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", agebirthday("Jackson", 1)birthday(1, "Jackson”)birthday(name = "Jackson", age = 1)birthday(age = 1, name = "Jackson")

#using default parameter valuedef birthday(name = "Jackson", age = 1): print "Happy birthday,", name, "!", "You’re", agebirthday("Mike", 10)birthday(age = 10, name = "Mike")birthday(name = "Mike")

Guide to Programming with Python 14

Positional arguments: Arguments passed to the parameters in order

Keyword argument: Argument passed to a specific parameter using the parameter nameThe biggest benefit of using keyword arguments is clarity.

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 argumentdef 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 Variablesdef func1(): local_name1 = "Func1” #local variable print local_name1, global_name #can access global_name but not local_name2def 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 herefunc1()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, value3value1 = 10value2 = 20value3 = 30print "In the global scope:", value1, value2, value3demo() # value1 is changed; value2 and value3 notprint "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 Pseudocodedisplay the game instructionsdetermine who goes firstcreate an empty tic-tac-toe boarddisplay the boardwhile 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 turnscongratulate the winner or declare a tie

Guide to Programming with Python 20

#define a function to avoid repeating the codes

#define a function to enhance readability

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 FunctionsPlanned functions for the Tic-Tac-Toe game

Guide to Programming with Python 22

Recursion

How would you describethis shape to someonewho couldn’t see it?

Sierpenski Gasket(a fractal)

We can make this shapewith a few simple rules.

Recursive Definitions

1. Start with an equilateral triangle.

2. Cut a triangular hole out of all current triangles.

3. Repeat 2) forever.

Recursive Definitions

This shape is created through the use of recursion.

Recursive functions make use of their own previous values in their definitions.

Recursion works by breaking a larger problem down into steps, each of which is smaller than the last one. You stop when you reach some smallest step called the basis.

Recursive Definitions

Recursive function example:– Basis: f(0) = 3– Recursive step: f(n+1) = 2*f(n) + 3

– What’s f(1)?– What’s f(2)?

Factorial Function Factorial : x! = all the numbers from 1 to x

multiplied together. 5! = 5 * 4 * 3 * 2 * 1

We can redefine f(n) = n! recursively. How? – Basis: f(1) = 1– Recursive step: f(n) = n * f(n-1).

Find your partner and write the factorial(num) function using recursion!We’ll do this one as a fill-in-the-blanks.

Factorial PseudocodeThis function takes a number

If the number is 1, we’re at the basis return a 1 Otherwise, we need to recur

return the number * the next step

Factorialdef factorial(num): if ___ __ _: return _ else : return ___* factorial(___ _ _)

print factorial(5)

Fibonacci numbers

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,..

In the Fibonacci sequence of numbers, each number is the sum of the previous two numbers, starting with 0 and 1

Fibonacci function (recursion with 2 bases):– f(0) = 0– f(1) = 1– f(n+2) = f(n) + f(n+1)

Fibonacci

def fabonacci(num): if num == 0: return 0 elif num == 1: return 1 else: return fabonacci(num - 1) + fabonacci(num - 2)

print "fabonacci numbers: "for i in range(20): print fabonacci(i),print

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 32

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 33

top related