1 / 33

Guide to Programming with Python

This guide explains the use of functions in programming with Python, specifically focusing on the Tic-Tac-Toe game. It covers topics such as creating functions, accepting parameters, returning values, working with global variables, and creating a computer opponent.

karenavila
Download Presentation

Guide to Programming with Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game

  2. 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

  3. 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

  4. 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

  5. Breakdown of the Tic-Tac-Toe Game display the game instructions determine who goes first create an empty tic-tac-toe board display the board 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 #define a function to enhance readability #define a function to avoid repeating the codes Guide to Programming with Python

  6. 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

  7. 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

  8. Calling a Function instructions() • Call tells the computer to execute functioninstructions() • Call works just like call to built-in function • Tells the computer to execute previously-defined function Guide to Programming with Python

  9. Abstraction • Abstraction: Mechanism that lets you think about the big picture without worrying about the details • Functions facilitate abstraction • Can call functioninstructions()without worrying about the details Guide to Programming with Python

  10. 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

  11. 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

  12. Returning Information through Return Values def give_me_five(): five = 5 return five • Return value: A value returned by a function • returnstatement returns values from a function • returnstatement 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

  13. 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") throughresponse • Sample call: answer = ask_yes_no("Enter y or n: ") Guide to Programming with Python

  14. Positional Parameters & Positional versus Keyword Arguments def birthday(name, age): print "Happy birthday,", name, "!", "You’re", age birthday("Jackson", 1) birthday(1, "Jackson”) birthday(name = "Jackson", age = 1) birthday(age = 1, name = "Jackson") #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") Positional arguments: Arguments passed to the parameters in order Keyword argument: Argument passed to a specific parameter using the parameter name The biggest benefit of using keyword arguments is clarity. Guide to Programming with Python

  15. 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

  16. 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

  17. Global versus Local Variables def func1(): local_name1 = "Func1” #local variable print local_name1, global_name #can 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

  18. 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

  19. 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

  20. Tic-Tac-Toe Pseudocode display the game instructions determine who goes first create an empty tic-tac-toe board display the board 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 #define a function to enhance readability #define a function to avoid repeating the codes Guide to Programming with Python

  21. 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

  22. Tic-Tac-Toe Functions Table 6.1: Tic-Tac-Toe Functions Planned functions for the Tic-Tac-Toe game Guide to Programming with Python

  23. 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.

  24. Recursive Definitions • Start with an equilateral triangle. • Cut a triangular hole out of all current triangles. • Repeat 2) forever.

  25. 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.

  26. 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)?

  27. 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.

  28. Factorial Pseudocode This 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

  29. Factorial def factorial(num): if ___ __ _: return _ else : return ___* factorial(___ _ _) print factorial(5)

  30. 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)

  31. 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

  32. Summary • What you need to know about functions • Using keyword defto 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

  33. 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

More Related