Guide to Programming with Python

Slides:



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

Copyright © 2014 Dr. James D. Palmer; This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
PLANNING THE TIC TAC TOE GAME BY NEEL DAVE. TIC TAC TOE INSTRUCTIONS Tic Tac Toe Instructions The basic concept of Tic Tac Toe 1.This is a game for two.
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.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
Guide to Programming with Python
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
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.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
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.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Course A201: Introduction to Programming 11/04/2010.
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.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Computers and Scientific Thinking David Reed, Creighton University Functions and Libraries 1.
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.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 5 Function Interfaces 4/18/09 Python Mini-Course: Day 2 - Lesson 5 1.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Python Functions.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 17 Parameters, Scope, Return values.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
JavaScript, Fourth Edition
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Python Let’s get started!.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
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.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
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.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Positional Parameters and Global Variables
Chapter 9: Value-Returning Functions
Programming Logic and Design Seventh Edition
Topics Introduction to Functions Defining and Calling a Void Function
Python Let’s get started!.
CS 1110 Introduction to Programming Spring 2017
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
Chapter 4 void Functions
Programming Logic and Design Fourth Edition, Comprehensive
Topics Introduction to Functions Defining and Calling a Void Function
Functions Christopher Harrison | Content Developer
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
Starting Out with Programming Logic & Design
Introduction to Computer Science
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
def-ining a function A function as an execution control structure
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Chapter 4: Writing and Designing a Complete Program
Presentation transcript:

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

Objectives 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

The Tic-Tac-Toe Game Figure 6.1: Instructions screen of the Tic-Tac-Toe game The computer is full of... confidence. Guide to Programming with Python

The Tic-Tac-Toe Game (continued) Figure 6.2: The computer wins the Tic-Tac-Toe game. With just simple programming, the computer plays a decent game. Guide to Programming with Python

The Tic-Tac-Toe Game (continued) Figure 6.3: The computer loses the Tic-Tac-Toe game. The computer’s simple programming allows it to be beat. Guide to Programming with Python

The Instructions Program Figure 6.4: Sample run of the Instructions program Instructions are displayed each time with a single call to a function. Guide to Programming with Python

Creating Functions Can define functions of your own Functions let you to break up code into manageable chunks Programs that are a long series of instructions are hard to write, understand, and maintain Just like built-in functions, your new functions should do one job well Guide to Programming with Python

Defining a Function 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

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

Calling a Programmer-Created 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 instructions.py Guide to Programming with Python

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 Like inverse of “progressive refinement” Guide to Programming with Python

Using Parameters and Return Values Just as with built-in functions Your functions can get values Your functions can return values Guide to Programming with Python

The Receive and Return Program Figure 6.5: Sample run of the Receive and Return program Functions use a parameter, a return value, or both. Guide to Programming with Python

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

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

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 created in a function cannot be directly accessed outside the function Parameters and return values allow for information exchange Guide to Programming with Python

Receiving and Returning Values in the Same Function 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: ") receive_and_return.py Guide to Programming with Python

Software Reuse Software reuse: Leveraging existing software in a new project Software Reuse can: Increase productivity Improve software quality Provide consistency across products Improve software performance Guide to Programming with Python

Using Keyword Arguments and Default Parameter Values Can pass values to specific parameters Can give parameters default values Guide to Programming with Python

The Birthday Wishes Program Figure 6.6: Sample run of the Birthday Wishes program Keyword arguments and default parameter values add flexibility. Guide to Programming with Python

Positional Parameters and Positional Arguments def birthday1(name, age): print "Happy birthday,", name, "!", "You’re", age, ". " Positional parameters: A list of names in a function header name and age are positional parameters Guide to Programming with Python

Positional Parameters and Positional Arguments (continued) >>> birthday1("Jackson", 1) Happy birthday, Jackson! You're 1. >>> birthday1(1, "Jackson") Happy birthday, 1! You're Jackson. Positional arguments: A list of argument values in a function call With positional parameters and positional arguments, parameters get their values based on the order of the values sent Guide to Programming with Python

Positional Parameters and Keyword Arguments >>> birthday1(name = "Jackson", age = 1) Happy birthday, Jackson! You're 1. >>> birthday1(age = 1, name = "Jackson") Keyword argument: Argument passed to a specific parameter using the parameter name Guide to Programming with Python

Default Parameter Values def birthday2(name = "Jackson", age = 1): print "Happy birthday,", name, "!", "You’re", age, ". " Default parameter value: A value that a parameter gets if no value is passed to it Guide to Programming with Python

Default Parameter Values (continued) def birthday2(name = "Jackson", age = 1): print "Happy birthday,", name, "!", "You’re", age, ". " Default Parameter Values (continued) >>> birthday2() Happy birthday, Jackson! You're 1. >>> birthday2(name = "Katherine") Happy birthday, Katherine! You're 1. >>> birthday2(age = 12) Happy birthday, Jackson! You're 12. >>> birthday2(name = "Katherine", age = 12) Happy birthday, Katherine! You're 12. >>> birthday2("Katherine", 12) >>> birthday2(12, "Katherine") Happy birthday, 12! You're Katherine. birthday_wishes.py Guide to Programming with Python

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 Guide to Programming with Python

Scopes (continued) Figure 6.7: Visual representation of program scopes Three scopes: one for each function, one for the global scope Guide to Programming with Python

Using Global Variables and Constants Global variables are variables that can be accessed in any part of a program Global constants are constants that can be accessed in any part of a program Guide to Programming with Python

The Global Reach Program Figure 6.8: Sample run of the Global Reach program Global variables can be accessed inside any function. Guide to Programming with Python

Reading a Global Variable from Inside a Function def read_global(): print "Inside read_global(), value is:", value value = 10 print "In the global scope, value is:", value, "\n" read_global() print "Back in the global scope, value is:", value, "\n" Guide to Programming with Python

Reading a Global Variable from Inside a Function (continued) Global variable: A variable created in the global scope that can be accessed in any part of a program Local variable: A variable created in a scope other than the global scope that can't be accessed outside of its scope Can read the value of a global variable from within any scope in your program Guide to Programming with Python

Shadowing a Global Variable from Inside a Function def shadow_global(): value = -10 print "Inside shadow_global(), value is:", value value = 10 shadow_global() print "Back in global scope, value is still:", value 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

Changing a Global Variable from Inside a Function def change_global(): global value value = -10 print "Inside change_global(), value is:", value value = 10 change_global() print "Back in the global scope, value is now:", value Can gain direct access to global variable with keyword global global_reach.py Guide to Programming with Python

Mutable Sequences Can Be Changed Inside Functions def change_list(the_list): the_list[1] = "changed" my_list = ["same", "same", "same"] print my_list change_list(my_list) Guide to Programming with Python

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

Planning the Tic-Tac-Toe Game Figure out how game should behave (inputs & outputs) Figure out how to represent the data Pseudocode List of functions Code Run the tic-tac-toe.py program now, but don’t show its code yet tic-tac-toe.py (run only) Guide to Programming with Python

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

Representing the Tic-Tac-Toe Data (continued) Figure 6.9: Visual representation of the game board Each square number corresponds to a position in the list. Guide to Programming with Python

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 switch turns congratulate the winner or declare a tie Guide to Programming with Python

Tic-Tac-Toe Functions display the game instructions display_instruct() determine who goes first (gets X) pieces() – returns human, computer (X and O) create an empty tic-tac-toe board new_board() – returns an empty board display the board display_board(board) while nobody’s won and it’s not a tie winner(board) – returns a piece, ‘TIE’, or None if it’s the human’s turn get the human’s move human_move(board, human) – returns move update the board with the move otherwise calculate the computer’s move computer_move(board,human,computer) switch turns next_turn(turn) – returns turn (X or O) congratulate the winner or declare a tie congrat_winner(winner,human,computer) ask_yes_no(question), ask_number(question, low, high), legal_moves(board) display the game instructions display_instruct() determine who goes first (gets X) pieces() – returns human, computer (X and O) create an empty tic-tac-toe board new_board() – returns an empty board display the board display_board(board) while nobody’s won and it’s not a tie winner(board) – returns a piece, ‘TIE’, or None if it’s the human’s turn get the human’s move human_move(board, human) – returns move update the board with the move otherwise calculate the computer’s move computer_move(board,human,computer) switch turns next_turn(turn) – returns turn (X or O) congratulate the winner or declare a tie congrat_winner(winner,human,computer) ask_yes_no(question), ask_number(question, low, high), legal_moves(board) Guide to Programming with Python

Tic-Tac-Toe Main display the game instructions display_instruct() determine who goes first (gets X) computer, human = pieces() turn = X create an empty tic-tac-toe board board = new_board() display the board display_board(board) while nobody’s won and it’s not a tie while not winner(board): if it’s the human’s turn if turn == human: get the human’s move move = human_move(board, human) update the board with the move board[move] = human otherwise else: calculate the computer’s move move = cmptr_mv(brd,hmn,cmptr) update the board with the move board[move] = computer display the board display_board(board) switch turns turn = next_turn(turn) winner = winner(board) congratulate the winner or declare a tie congrat_winner(winner,human,computer) display the game instructions display_instruct() determine who goes first (gets X) computer, human = pieces() turn = X create an empty tic-tac-toe board board = new_board() display the board display_board(board) while nobody’s won and it’s not a tie while not winner(board): if it’s the human’s turn if turn == human: get the human’s move move = human_move(board, human) update the board with the move board[move] = human otherwise else: calculate the computer’s move move = cmptr_mv(brd,hmn,cmptr) update the board with the move board[move] = computer display the board display_board(board) switch turns turn = next_turn(turn) winner = winner(board) congratulate the winner or declare a tie congrat_winner(winner,human,computer) Guide to Programming with Python

Computer Move Pseudocode if computer can win, pick that move if human can win, block that move take “best” open square tic-tac-toe.py Guide to Programming with Python

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

Tic-Tac-Toe Functions (continued) Table 6.1 (continued): Tic-Tac-Toe Functions Planned functions for the Tic-Tac-Toe game Guide to Programming with Python

Summary What keyword do you use to define a function? What is a function header? The line that defines the function What is a docstring? a triple-quoted string that immediately follows a function header and that documents what the function does What is abstraction? a mechanism that lets you think about the big picture without worrying about the details (think functions) What is a parameter? a variable/name in a function header that can receive a value What is an argument? a value used in a function call that’s passed to a parameter Guide to Programming with Python

Summary (continued) What is a return value? What is encapsulation? a value returned by a function What is encapsulation? a technique of keeping independent code separate by hiding the details Can variables and parameters created in a function be directly accessed outside the function? No! What is software reuse? leveraging existing software in a new project What is a keyword argument? an argument passed to a specific parameter of a function by using its parameter name Guide to Programming with Python

Summary (continued) How do you provide a default parameter value in a function? use name = value in the function header What do you call different areas of a program that are separate from each other? scopes What is a global variable? a variable created in the global scope that can be accessed in any part of a program What is a local variable? a variable created in a scope other than the global scope that can’t be accessed outside of its scope You should avoid using global variables (but global constants are good) Guide to Programming with Python