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.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

Guide to Programming with Python
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Introduction to Methods
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
INTRODUCTION TO PROGRAMMING STRUCTURE Chapter 4 1.
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.
Invitation to Computer Science, Java Version, Second Edition.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
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.
1 Functions Lecfture Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Computers and Scientific Thinking David Reed, Creighton University Functions and Libraries 1.
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 Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
For loops in programming Assumes you have seen assignment statements and print statements.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 CS161 Introduction to Computer Science Topic #9.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
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.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
CS001 Introduction to Programming Day 2 Sujana Jyothi
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Python Let’s get started!.
Modularity using Functions Chapter 4. Modularity In programming blocks of code often can be "called up" and reused whenever necessary, for example code.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
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.
JavaScript Modularity. Goals By the end of this lecture, you should … Understand why programmers use modularity. Understand how to create a function in.
COSC 1223 Computer Science Concepts I Joe Bryan. What is a function? Like a mini-program that performs a specific task Two types: Built-in functions Functions.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
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.
Topics Introduction to Functions Defining and Calling a Void Function
Course A201: Introduction to Programming
Python Let’s get started!.
COMP 170 – Introduction to Object Oriented Programming
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Chapter 6 Functions.
Functions CIS 40 – Introduction to Programming in Python
Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 3 Simple Functions
Python Primer 2: Functions and Control Flow
Chapter 4 void Functions
Programming Logic and Design Fourth Edition, Comprehensive
Topics Introduction to Functions Defining and Calling a Void Function
Topics Introduction to Functions Defining and Calling a Function
Object Oriented Programming in java
COMPUTER PROGRAMMING SKILLS
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
Functions, Procedures, and Abstraction
Presentation transcript:

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 into your functions through parameters 0 Return information from your functions through return values 0 Work with global variables and constants 0 Create a computer opponent that plays a strategy game

Creating Functions 0 Python lets you create your own functions that will go off and perform a specific task that you have designed. 0 This allows you to break up your code into more manageable chunks. 0 Programs that are one, long series of instructions with no logical breaks are hard to write, understand, maintain, and work with.

Instructions Program # Instructions # Demonstrates programmer-created functions def instructions(): """Display game instructions.""" print( """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, The number will correspond to the board position as illustrated: 0 | 1 | | 4 | | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n """ ) # main print("Here are the instructions to the Tic-Tac-Toe game:") instructions() print("Here they are again:") instructions() print("You probably understand the game by now.") input("\n\nPress the enter key to exit.")

Defining a Function # Instructions # Demonstrates programmer-created functions def instructions(): """Display game instructions.""" print( """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, The number will correspond to the board position as illustrated: 0 | 1 | | 4 | | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n """ ) # main print("Here are the instructions to the Tic-Tac-Toe game:") instructions() print("Here they are again:") instructions() print("You probably understand the game by now.") input("\n\nPress the enter key to exit.") This line tells the computer that the block of code that follows is to be used together as the function instructions(). This line and its block are called a function definition. They define what the function does, but don’t actually run the function. The computer makes a note this functions exists so it can use it later.

0 To define a function on your own, start with def, followed by your function name, followed by a pair of parentheses, followed by a colon, and then your indented block of statements. 0 To name a function, follow the basic rules for naming variables. Your function name should convey what the function produces or does. Defining a Function

Documenting a Function # Instructions # Demonstrates programmer-created functions def instructions(): """Display game instructions.""" print( """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, The number will correspond to the board position as illustrated: 0 | 1 | | 4 | | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n """ ) # main print("Here are the instructions to the Tic-Tac-Toe game:") instructions() print("Here they are again:") instructions() print("You probably understand the game by now.") input("\n\nPress the enter key to exit.") Called a docstring or documentation string Typically a triple quoted string that defines what the function does You do not have to use one, but if you do it must be in the first line of your function.

Calling a Function # Instructions # Demonstrates programmer-created functions def instructions(): """Display game instructions.""" print( """ Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor. You will make your move known by entering a number, The number will correspond to the board position as illustrated: 0 | 1 | | 4 | | 7 | 8 Prepare yourself, human. The ultimate battle is about to begin. \n """ ) # main print("Here are the instructions to the Tic-Tac-Toe game:") instructions() print("Here they are again:") instructions() print("You probably understand the game by now.") input("\n\nPress the enter key to exit.") Whenever the function instructions() are called in this program, this block of code will run. To call a function, use the name of the function followed by a set of parentheses. This tells the computer to go off and execute the function defined earlier.

Understanding Abstraction By writing and calling functions you are practicing abstraction. This means that you think about the big pictures without worrying about the details. For example, you can type instructions( ) without having to worry about what the instructions are.

Using Parameters and Return Values #Receive and Return #Demonstrates parameters and return values def display(message): print(message) def give_me_five(): five = 5 return five def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = input(question).lower() return response # main display ("Here's a message for you. \n") number = give_me_five() print("Here's what I got from give_me_five():",number) answer = ask_yes_no("\nPlease enter 'y' or 'n': ") print("Thanks for entering: ", answer) input("\n\nPress the enter key to exit.") Three different functions: This function receives a value from the user This function returns a value This function receives and returns a value

Receiving Information Through Parameters #Receive and Return #Demonstrates parameters and return values def display(message): print(message) def give_me_five(): five = 5 return five def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = input(question).lower() return response # main display ("Here's a message for you. \n") number = give_me_five() print("Here's what I got from give_me_five():",number) answer = ask_yes_no("\nPlease enter 'y' or 'n': ") print("Thanks for entering: ", answer) input("\n\nPress the enter key to exit.") The display( ) function, receives a value through its parameter. Parameters are essentially variable names inside the parentheses of a function header. Parameters get the values sent to the function from the function call through its arguments. So the function display ( ) takes in the string“Here’s a message for you.”, saves it to message, and then prints the message because that is what it is defined to do.

Note: If message hadn’t been passed a value display ( __) Then it would have generated an error. This function is set up to only have one parameter. To define functions with multiple parameters, list them out, separated by commas. Ex. import random def display(number1, number2): print(number1, number2) #main display(1, 2) This will print: 1 2

Returning Information through Return Values #Receive and Return #Demonstrates parameters and return values def display(message): print(message) def give_me_five(): five = 5 return five def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = input(question).lower() return response # main display ("Here's a message for you. \n") number = give_me_five() print("Here's what I got from give_me_five():",number) answer = ask_yes_no("\nPlease enter 'y' or 'n': ") print("Thanks for entering: ", answer) input("\n\nPress the enter key to exit.") This function returns a value through the return statement. When this line runs, the function passes the value of five back to the part of the program that called it, and then ends. This catches the return value of the function by assigning the result of the function call to number. (The program would work the same way if this was not here, but is used to catch the values returned by the function)

Note: A function always ends after it hits a return statement. You can pass more than one value back from a function. Just list all the values you want to return, separated by commas. Ex: def give_five(): five = int(input("Give me a number")) four = int(input("How about another number")) return five, four number = give_five() print("Here's what I got from this:", number) This gives you: Give me a number 5 How about another number 10 Here's what I got from this: (5, 10)

Understanding Encapsulation “You might not see the need for return values when using your own functions. Why not just use the variable five back in the main part of the program? Because you can’t. five doesn’t exist outside of its function give_me_five(). In fact, no variable you create in a function, including its parameters, can be directly accessed outside its function. This is a good thing and it is called encapsulation. Encapsulation helps keep independent code truly separate by hiding or encapsulating the details. That’s why you use parameters and return values: to communicate just the information that needs to be exchanged. Plus you don’t have to keep track of the variables you create within a function in the rest of the program. As your programs get larger this is a great benefit.”

Receiving and Returning Values in the Same Function This function receives and returns a value. It receives a question and returns a response from the user. Def ask_yes_no(question): “””Ask a yes or no question””” response = None while response not in (“y”,”n”): response = input(question).lower() return response #main answer = ask_yes_no(“\nPlease enter ‘y’ or ‘n”: “) print(“Thanks for entering:”, answer) Question gets the value of the argument passed to the function. In this case: The while loop keeps asking the question until the user enters y or n. It always converts their answer to lowercase. When they have entered a valid response, it send the string back to the part of the program that called it.

Software Reuse One benefit to using functions is that they can easily be reused in other programs. To reuse functions you can: - Copy them into your new program - Create your own modules and import your functions into a new program, just like import random. Information about this can be found in Ch. 9