Read Aloud the Text Content
This audio was created by Woord's Text to Speech service by content creators from all around the world.
Text Content or SSML code:
5.1: Introduction to Functions CONCEPT: A function is a group of statements that exist within a program for the purpose of performing a specific task. In Chapter 2, we described a simple algorithm for calculating an employee’s pay. In the algorithm, the number of hours worked is multiplied by an hourly pay rate. A more realistic payroll algorithm, however, would do much more than this. In a real-world application, the overall task of calculating an employee’s pay would consist of several subtasks, such as the following: Getting the employee’s hourly pay rate Getting the number of hours worked Calculating the employee’s gross pay Calculating overtime pay Calculating withholdings for taxes and benefits Calculating the net pay Printing the paycheck Most programs perform tasks that are large enough to be broken down into several subtasks. For this reason, programmers usually break down their programs into small manageable pieces known as functions. A function is a group of statements that exist within a program for the purpose of performing a specific task. Instead of writing a large program as one long sequence of statements, it can be written as several small functions, each one performing a specific part of the task. These small functions can then be executed in the desired order to perform the overall task. This approach is sometimes called divide and conquer because a large task is divided into several smaller tasks that are easily performed. Figure 5-1 illustrates this idea by comparing two programs: one that uses a long complex sequence of statements to perform a task, and another that divides a task into smaller tasks, each of which is performed by a separate function. When using functions in a program, you generally isolate each task within the program in its own function. For example, a realistic pay calculating program might have the following functions: A function that gets the employee’s hourly pay rate A function that gets the number of hours worked A function that calculates the employee’s gross pay A function that calculates the overtime pay A function that calculates the withholdings for taxes and benefits A function that calculates the net pay A function that prints the paycheck A program that has been written with each task in its own function is called a modularized program. Figure 5-1 Using functions to divide and conquer a large task The figure consists of two parts that describe one long sequence of statements and a set of functions. Figure (1):There are twenty four lines and each line consists of the word statement. Note: This program is one long, complex sequence of statements. Figure (2): There are four rectangular sections. Each section defines a function as follows. Line 1 at indentation level 0: def function1 open round bracket close bracket colon. Line 2 at indentation level 1: statement. Line 3 at indentation level 1: statement. Line 4 at indentation level 1: statement. Line 5 at indentation level 0: def function2 open round bracket close bracket colon. Line 6 at indentation level 1: statement. Line 7 at indentation level 1: statement. Line 8 at indentation level 1: statement. Line 9 at indentation level 0: def function3 open round bracket close bracket colon. Line 10 at indentation level 1: statement. Line 11 at indentation level 1: statement. Line 12 at indentation level 1: statement. Line 13 at indentation level 0: def function4 open round bracket close bracket colon. Line 14 at indentation level 1: statement. Line 15 at indentation level 1: statement. Line 16 at indentation level 1: statement. Note: In this program the task has been divided into smaller tasks, each of which is performed by a separate function. Benefits of Modularizing a Program with Functions A program benefits in the following ways when it is broken down into functions: Simpler Code A program’s code tends to be simpler and easier to understand when it is broken down into functions. Several small functions are much easier to read than one long sequence of statements. Code Reuse Functions also reduce the duplication of code within a program. If a specific operation is performed in several places in a program, a function can be written once to perform that operation, then be executed any time it is needed. This benefit of using functions is known as code reuse because you are writing the code to perform a task once, then reusing it each time you need to perform the task. Better Testing When each task within a program is contained in its own function, testing and debugging becomes simpler. Programmers can test each function in a program individually, to determine whether it correctly performs its operation. This makes it easier to isolate and fix errors. Faster Development Suppose a programmer or a team of programmers is developing multiple programs. They discover that each of the programs perform several common tasks, such as asking for a username and a password, displaying the current time, and so on. It doesn’t make sense to write the code for these tasks multiple times. Instead, functions can be written for the commonly needed tasks, and those functions can be incorporated into each program that needs them. Easier Facilitation of Teamwork Functions also make it easier for programmers to work in teams. When a program is developed as a set of functions that each performs an individual task, then different programmers can be assigned the job of writing different functions. Void Functions and Value-Returning Functions In this chapter, you will learn to write two types of functions: void functions and value-returning functions. When you call a void function, it simply executes the statements it contains and then terminates. When you call a value-returning function, it executes the statements that it contains, then returns a value back to the statement that called it. The input function is an example of a value-returning function. When you call the input function, it gets the data that the user types on the keyboard and returns that data as a string. The int and float functions are also examples of value-returning functions. You pass an argument to the int function, and it returns that argument’s value converted to an integer. Likewise, you pass an argument to the float function, and it returns that argument’s value converted to a floating-point number. The first type of function that you will learn to write is the void function. Self-review This won't affect your score Checkpoint 5.1-1 3 tries left A ________ is a group of statements that exist within a program for the purpose of performing a specific task. blueprint paradigm protocol function Self-review This won't affect your score Checkpoint 5.1-2 3 tries left A large task is divided into several smaller tasks that are easily performed. This technique is known as _________. get and set break and build pass and process divide and conquer Self-review This won't affect your score Checkpoint 5.1-3 1 try left If a specific operation is performed in several places in a program, a function can be written once to perform that operation, and then be reused any time it is needed. True False 5.2: Defining and Calling a Void Function CONCEPT: The code for a function is known as a function definition. To execute the function, you write a statement that calls it. Function Names Before we discuss the process of creating and using functions, we should mention a few things about function names. Just as you name the variables that you use in a program, you also name the functions. A function’s name should be descriptive enough so anyone reading your code can reasonably guess what the function does. Python requires that you follow the same rules that you follow when naming variables, which we recap here: You cannot use one of Python’s keywords as a function name. (See Table 1-2 for a list of the keywords.) A function name cannot contain spaces. The first character must be one of the letters a through z, A through Z, or an underscore character (_). After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or underscores. Uppercase and lowercase characters are distinct. Because functions perform actions, most programmers prefer to use verbs in function names. For example, a function that calculates gross pay might be named calculate_gross_pay. This name would make it evident to anyone reading the code that the function calculates something. What does it calculate? The gross pay, of course. Other examples of good function names would be get_hours, get_pay_rate, calculate_overtime, print_check, and so on. Each function name describes what the function does. Self-review This won't affect your score Checkpoint 5.2-1 3 tries left A function definition has two parts: _________. a function header and a block an ID and variable list an entry and an exit a key and an access list 5.3: Designing a Program to Use Functions CONCEPT: Programmers commonly use a technique known as top-down design to break down an algorithm into functions. Flowcharting a Program with Functions In Chapter 2, we introduced flowcharts as a tool for designing programs. In a flowchart, a function call is shown with a rectangle that has vertical bars at each side, as shown in Figure 5-8. The name of the function that is being called is written on the symbol. The example shown in Figure 5-8 shows how we would represent a call to the message function. Figure 5-8 Function call symbol The figure illustrates the function call symbol. A rectangle has a vertical bar at the left and right ends. The rectangle contains the text, message open round bracket. Programmers typically draw a separate flowchart for each function in a program. For example, Figure 5-9 shows how the main function and the message function in Program 5-2 would be flowcharted. When drawing a flowchart for a function, the starting terminal symbol usually shows the name of the function and the ending terminal symbol usually reads Return. Figure 5-9 Flowchart for Program 5-2 The figure illustrates two flowcharts. The image contains two flowcharts. Flowchart 1: The following flowchart is depicted as a flow of a rectangle, ellipses and parallelograms. main () contains Display 'I have a message for you. Display 'I have a message for you. contains message (). message () contains Display 'Goodbye! '. Display 'Goodbye! ' contains Return. Flowchart 2: The following flowchart is depicted as a flow of ellipses and parallelograms. message () contains Display 'I am Arthur'. Display 'I am Arthur' contains Display 'King of the Britons'. Display 'King of the Britons' contains Return. Top-Down Design In this section, we have discussed and demonstrated how functions work. You’ve seen how control of a program is transferred to a function when it is called, then returns to the part of the program that called the function when the function ends. It is important that you understand these mechanical aspects of functions. Just as important as understanding how functions work is understanding how to design a program that uses functions. Programmers commonly use a technique known as top-down design to break down an algorithm into functions. The process of top-down design is performed in the following manner: The overall task that the program is to perform is broken down into a series of subtasks. Each of the subtasks is examined to determine whether it can be further broken down into more subtasks. This step is repeated until no more subtasks can be identified. Once all of the subtasks have been identified, they are written in code. This process is called top-down design because the programmer begins by looking at the topmost level of tasks that must be performed and then breaks down those tasks into lower levels of subtasks. Hierarchy Charts Flowcharts are good tools for graphically depicting the flow of logic inside a function, but they do not give a visual representation of the relationships between functions. Programmers commonly use hierarchy charts for this purpose. A hierarchy chart, which is also known as a structure chart, shows boxes that represent each function in a program. The boxes are connected in a way that illustrates the functions called by each function. Figure 5-10 shows an example of a hierarchy chart for a hypothetical pay calculating program. Figure 5-10 A hierarchy chart The figure illustrates a flowchart with three branches. The following flowchart is depicted as a flow of rectangles. main() contains get_input (), calc_gross_pay (), calc_overtime (), calc_withholdings() and calc_net_pay (). get_input () contains get_hours_worked () and get_hourly_rate(). calc_withholdings() contains calc_benefits (), and calc_taxes (). The chart shown in Figure 5-10 shows the main function as the topmost function in the hierarchy. The main function calls five other functions: get_input, calc_gross_pay, calc_overtime, calc_withholdings, and calc_net_pay. The get_input function calls two additional functions: get_hours_worked and get_hourly_rate. The calc_withholdings function also calls two functions: calc_taxes and calc_benefits. Notice the hierarchy chart does not show the steps that are taken inside a function. Because they do not reveal any details about how functions work, they do not replace flowcharts or pseudocode. Self-review This won't affect your score Checkpoint 5.3-1 1 try left In top-down design, tasks are broken down into subtasks until no more subtasks can be identified. True False Self-review This won't affect your score Checkpoint 5.3-2 3 tries left What is the last step in top-down design? Break down the major tasks. Code the subtasks. Combine the subtasks. Order the tasks/ In the Spotlight: Defining and Calling Functions Professional Appliance Service, Inc. offers maintenance and repair services for household appliances. The owner wants to give each of the company’s service technicians a small handheld computer that displays step-by-step instructions for many of the repairs that they perform. To see how this might work, the owner has asked you to develop a program that displays the following instructions for disassembling an Acme laundry dryer: Step 1: Unplug the dryer and move it away from the wall. Step 2: Remove the six screws from the back of the dryer. Step 3: Remove the dryer’s back panel. Step 4: Pull the top of the dryer straight up. During your interview with the owner, you determine that the program should display the steps one at a time. You decide that after each step is displayed, the user will be asked to press the Enter key to see the next step. Here is the algorithm in pseudocode: Display a starting message, explaining what the program does. Ask the user to press Enter to see step 1. Display the instructions for step 1. Ask the user to press Enter to see the next step. Display the instructions for step 2. Ask the user to press Enter to see the next step. Display the instructions for step 3. Ask the user to press Enter to see the next step. Display the instructions for step 4. This algorithm lists the top level of tasks that the program needs to perform and becomes the basis of the program’s main function. Figure 5-11 shows the program’s structure in a hierarchy chart. Figure 5-11 Hierarchy chart for the program The figure illustrates a flowchart with two branches. The following flowchart is depicted as a flow of rectangles. main () contains startup_message (), step1 (), step2 (), step3 () and step4 (). As you can see from the hierarchy chart, the main function will call several other functions. Here are summaries of those functions: startup_message. This function will display the starting message that tells the technician what the program does. step1. This function will display the instructions for step 1. step2. This function will display the instructions for step 2. step3. This function will display the instructions for step 3. step4. This function will display the instructions for step 4. Between calls to these functions, the main function will instruct the user to press a key to see the next step in the instructions. Program 5-3 shows the code for the program. Program 5-3 (acme_dryer.py) # This program displays step-by-step instructions # for disassembling an Acme dryer. # The main function performs the program's main logic. def main(): # Display the start-up message. startup_message() input('Press Enter to see Step 1.') # Display step 1. step1() input('Press Enter to see Step 2.') # Display step 2. step2() input('Press Enter to see Step 3.') # Display step 3. step3() input('Press Enter to see Step 4.') # Display step 4. step4() # The startup_message function displays the # program's initial message on the screen. def startup_message(): print('This program tells you how to') print('disassemble an ACME laundry dryer.') print('There are 4 steps in the process.') print() # The step1 function displays the instructions # for step 1. def step1(): print('Step 1: Unplug the dryer and') print('move it away from the wall.') print() # The step2 function displays the instructions # for step 2. def step2(): print('Step 2: Remove the six screws') print('from the back of the dryer.') print() # The step3 function displays the instructions # for step 3. def step3(): print('Step 3: Remove the back panel') print('from the dryer.') print() # The step4 function displays the instructions # for step 4. def step4(): print('Step 4: Pull the top of the') print('dryer straight up.') # Call the main function to begin the program. main() Program Output This program tells you how to disassemble an ACME laundry dryer. There are 4 steps in the process. Press Enter to see Step 1. [Enter] Step 1: Unplug the dryer and move it away from the wall. Press Enter to see Step 2. [Enter] Step 2: Remove the six screws from the back of the dryer. Press Enter to see Step 3. [Enter] Step 3: Remove the back panel from the dryer. Press Enter to see Step 4. [Enter] Step 4: Pull the top of the dryer straight up. Start Animation Pausing Execution Until the User Presses Enter Sometimes you want a program to pause so the user can read information that has been displayed on the screen. When the user is ready for the program to continue execution, he or she presses the Enter key and the program resumes. In Python, you can use the input function to cause a program to pause until the user presses the Enter key. Line 7 in Program 5-3 is an example: input('Press Enter to see Step 1.') This statement displays the prompt 'Press Enter to see Step 1.' and pauses until the user presses the Enter key. The program also uses this technique in lines 10, 13, and 16. Self-review This won't affect your score Checkpoint 5.3-3 3 tries left In Python, you can use the ________ function to cause a program to pause until the user presses the Enter key. input hibernate stop pause Using the pass Keyword Sometimes when you are initially writing a program’s code, you know the names of the functions you plan to use, but you might not know all the details of the code that will be in those functions. When this is the case, you can use the pass keyword to create empty functions. Later, when the details of the code are known, you can come back to the empty functions and replace the pass keyword with meaningful code. For example, when we were writing the code for Program 5-3, we could have initially written empty function definitions for the step1, step2, step3, and step4 functions, as shown here: def step1(): pass def step2(): pass def step3(): pass def step4(): pass The pass keyword is ignored by the Python interpreter, so this code creates four functions that do nothing. TIP: The pass keyword can be used as a placeholder anywhere in your Python code. For example, it can be used in an if statement, as shown here: if x > y: pass else: pass Here is an example of a while loop that uses the pass keyword: while x < 100: pass 5.4: Local Variables CONCEPT: A local variable is created inside a function and cannot be accessed by statements that are outside the function. Different functions can have local variables with the same names because the functions cannot see each other's local variables. Anytime you assign a value to a variable inside a function, you create a local variable. A local variable belongs to the function in which it is created, and only statements inside that function can access the variable. (The term local is meant to indicate that the variable can be used only locally, within the function in which it is created.) An error will occur if a statement in one function tries to access a local variable that belongs to another function. For example, look at Program 5-4. Program 5-4 (bad_local.py) # Definition of the main function. def main(): get_name() print(f'Hello {name}.') # This causes an error! # Definition of the get_name function. def get_name(): name = input('Enter your name: ') # Call the main function. main() This program has two functions: main and get_name. In line 8, the name variable is assigned a value that is entered by the user. This statement is inside the get_name function, so the name variable is local to that function. This means that the name variable cannot be accessed by statements outside the get_name function. The main function calls the get_name function in line 3. Then, the statement in line 4 tries to access the name variable. This results in an error because the name variable is local to the get_name function, and statements in the main function cannot access it. Scope and Local Variables A variable’s scope is the part of a program in which the variable may be accessed. A variable is visible only to statements in the variable’s scope. A local variable’s scope is the function in which the variable is created. As you saw demonstrated in Program 5-4, no statement outside the function may access the variable. In addition, a local variable cannot be accessed by code that appears inside the function at a point before the variable has been created. For example, look at the following function. It will cause an error because the print function tries to access the val variable, but this statement appears before the val variable has been created. Moving the assignment statement to a line before the print statement will fix this error. def bad_function(): print(f'The value is {val}.') # This will cause an error! val = 99 Because a function’s local variables are hidden from other functions, the other functions may have their own local variables with the same name. For example, look at Program 5-5. In addition to the main function, this program has two other functions: texas and california. These two functions each have a local variable named birds. Program 5-5 (birds.py) # This program demonstrates two functions that # have local variables with the same name. def main(): # Call the texas function. texas() # Call the california function. california() # Definition of the texas function. It creates # a local variable named birds. def texas(): birds = 5000 print(f'texas has {birds} birds.') # Definition of the california function. It also # creates a local variable named birds. def california(): birds = 8000 print(f'california has {birds} birds.') # Call the main function. main() Program Output texas has 5000 birds. california has 8000 birds. Start Animation Although there are two separate variables named birds in this program, only one of them is visible at a time because they are in different functions. This is illustrated in Figure 5-12. When the texas function is executing, the birds variable that is created in line 13 is visible. When the california function is executing, the birds variable that is created in line 19 is visible. Figure 5-12 Each function has its own birds variable The figure illustrates birds variable in two functions. The image contains two Code snippets. Code snippet 1: Line 1 at indentation level 0: def texas open round bracket close round bracket colon. Line 2 at indentation level 1: birds equals 5000. Line 3 at indentation level 1: print open round bracket f single quote texas has open curly braces birds close curly braces birds dot single quote close round bracket. Line 4: birds right arrow 5000. Code snippet 2: Line 1 at indentation level 0: def california open round bracket close round bracket colon. Line 2 at indentation level 1: birds equals 8000. Line 3 at indentation level 1: print open round bracket f single quote texas has open curly braces birds close curly braces birds dot single quote close round bracket. Line 4: birds right arrow 8000. Self-review This won't affect your score Live Code Example 5.3 In the program below, the user makes an order. Fill in the commented line with the missing code to display the expected output. Expected Output: Hello, I would like to order. Enter your order: fries You have ordered fries # Definition of the main function. Self-review This won't affect your score Checkpoint 5.4-1 1 try left A local variable is declared inside a function, and only statements in the same function can access it. True False Self-review This won't affect your score Checkpoint 5.4-2 3 tries left A variable’s __________ specifies the part of a program in which a variable may be accessed. name attribute scope value Self-review This won't affect your score Checkpoint 5.4-3 1 try left A local variable in one function cannot have the same name as a local variable in a different function. True False