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

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

Guide to Programming with Python
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
Chapter 6: User-Defined Functions I
Introduction to Methods
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design First Edition by Tony Gaddis.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Python Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Python Let’s get started!.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Positional Parameters and Global Variables
Chapter 9: Value-Returning Functions
Topics Introduction to Functions Defining and Calling a Void Function
Python Let’s get started!.
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 6 Functions.
Functions CIS 40 – Introduction to Programming in Python
Chapter 5 - Functions Outline 5.1 Introduction
Starting Out with Programming Logic & Design
Chapter 3 Simple Functions
Functions, Procedures, and Abstraction
Chapter 4 void Functions
Programming Logic and Design Fourth Edition, Comprehensive
Topics Introduction to Functions Defining and Calling a Void Function
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
Starting Out with Programming Logic & Design
COMPUTER PROGRAMMING SKILLS
Functions, Procedures, and Abstraction
Lecture 6 - Recursion.
Presentation transcript:

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

What Do You See? Guide to Programming with Python2 Escher Circle limit IV 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 Python3

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 Python4

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 Guide to Programming with Python5 #define a function to avoid repeating the codes #define a function to enhance readability

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 Python6

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 Python7

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 Python8

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 Python9

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 Python10

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 Python12

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 Python13

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") Guide to Programming with Python14 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.

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 Python16

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 Python17

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 Python18

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 Python19

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 Guide to Programming with Python20 #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 Python21

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

Recursion  How would you describe this shape to someone who couldn’t see it?  Sierpenski Gasket (a fractal)  We can make this shape with 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 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

Factorial def 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 Python32

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 Python33