Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 6 Functions The Tic-Tac-Toe Game

2 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

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

4 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, 0 - 8. The number will correspond to the board position as illustrated: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 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.")

5 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, 0 - 8. The number will correspond to the board position as illustrated: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 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.

6 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

7 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, 0 - 8. The number will correspond to the board position as illustrated: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 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.

8 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, 0 - 8. The number will correspond to the board position as illustrated: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 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.

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

10 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

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

12 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

13 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)

14 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)

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

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

17 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


Download ppt "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."

Similar presentations


Ads by Google