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:

In the Spotlight: Passing an Argument to a Function Your friend Michael runs a catering company. Some of the ingredients that his recipes require are measured in cups. When he goes to the grocery store to buy those ingredients, however, they are sold only by the fluid ounce. He has asked you to write a simple program that converts cups to fluid ounces. You design the following algorithm: Display an introductory screen that explains what the program does. Get the number of cups. Convert the number of cups to fluid ounces and display the result. 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-15 shows the program’s structure in a hierarchy chart. Figure 5-15 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 intro () and cups_to_ounces (cups). As shown in the hierarchy chart, the main function will call two other functions. Here are summaries of those functions: intro. This function will display a message on the screen that explains what the program does. cups_to_ounces. This function will accept the number of cups as an argument and calculate and display the equivalent number of fluid ounces. In addition to calling these functions, the main function will ask the user to enter the number of cups. This value will be passed to the cups_to_ounces function. The code for the program is shown in Program 5-7. Program 5-7 (cups_to_ounces.py) # This program converts cups to fluid ounces. def main(): # display the intro screen. intro() # Get the number of cups. cups_needed = int(input('Enter the number of cups: ')) # Convert the cups to ounces. cups_to_ounces(cups_needed) # The intro function displays an introductory screen. def intro(): print('This program converts measurements') print('in cups to fluid ounces. For your') print('reference the formula is:') print(' 1 cup = 8 fluid ounces') print() # The cups_to_ounces function accepts a number of # cups and displays the equivalent number of ounces. def cups_to_ounces(cups): ounces = cups * 8 print(f'That converts to {ounces} ounces.') # Call the main function. main() Program Output (with input shown in bold) This program converts measurements in cups to fluid ounces. For your reference the formula is: 1 cup = 8 fluid ounces Enter the number of cups: 4 [Enter] That converts to 32 ounces. Start Animation Self-review This won't affect your score Live Code Example 5.4 This program takes a student ID from the user and prints it. However, it will fail on runtime due to an error. Correct the error to display the expected output. Sample Expected Output: Enter your student_ID: abcd1234 abcd1234 def main(): Passing Multiple Arguments Often it’s useful to write functions that can accept multiple arguments. Program 5-8 shows a function named show_sum, that accepts two arguments. The function adds the two arguments and displays their sum. Program 5-8 (multiple_args.py) # This program demonstrates a function that accepts # two arguments. def main(): print('The sum of 12 and 45 is') show_sum(12, 45) # The show_sum function accepts two arguments # and displays their sum. def show_sum(num1, num2): result = num1 + num2 print(result) # Call the main function. main() Program Output The sum of 12 and 45 is 57 Start Animation Notice two parameter variable names, num1 and num2, appear inside the parentheses in the show_sum function header. This is often referred to as a parameter list. Also notice a comma separates the variable names. The statement in line 6 calls the show_sum function and passes two arguments: 12 and 45. These arguments are passed by position to the corresponding parameter variables in the function. In other words, the first argument is passed to the first parameter variable, and the second argument is passed to the second parameter variable. So, this statement causes 12 to be assigned to the num1 parameter and 45 to be assigned to the num2 parameter, as shown in Figure 5-16. Figure 5-16 Two arguments passed to two parameters The figure illustrates two arguments passed to two parameters of a function. Line 1: def main open round bracket close round bracket colon at indentation level 0. Line 2: print open round bracket single quote The sum of 12 and 45 is single quote close round bracket at indentation level 1. Line 3: show underscore sum open round bracket 12 comma 45 close round bracket at indentation level 1. Line 4: def show underscore sum open round bracket num1 comma num2 close round bracket colon at indentation level 1. Line 5: result equals num1 plus num2 at indentation level 2. Line 6: print open round bracket result close round bracket at indentation level 2. Note: One box contains number 12, another box contains number 45. An arrow from num1 points to 12 and another arrow from num 2 points to 45. Suppose we were to reverse the order in which the arguments are listed in the function call, as shown here: show_sum(45, 12) This would cause 45 to be passed to the num1 parameter, and 12 to be passed to the num2 parameter. The following code shows another example. This time, we are passing variables as arguments. value1 = 2 value2 = 3 show_sum(value1, value2) When the show_sum function executes as a result of this code, the num1 parameter will be assigned the value 2, and the num2 parameter will be assigned the value 3. Program 5-9 shows one more example. This program passes two strings as arguments to a function. Program 5-9 (string_args.py) # This program demonstrates passing two string # arguments to a function. def main(): first_name = input('Enter your first name: ') last_name = input('Enter your last name: ') print('Your name reversed is') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) # Call the main function. main() Program Output (with input shown in bold) Enter your first name: Matt [Enter] Enter your last name: Hoyle [Enter] Your name reversed is Hoyle Matt Self-review This won't affect your score Live Code Example 5.5 The program below gets the number of units and the cost of each unit from the user. Replace the comments that appear in lines 6 and 7 with a statement that calls the show_total_cost function. As arguments, pass the num_units variable into the units parameter and pass the unit_cost variable into the cost parameter. Sample Expected Output Enter the number of units: 10 Enter the cost of each unit: 5.00 Total Cost: 50.00 def main(): Making Changes to Parameters When an argument is passed to a function in Python, the function parameter variable will reference the argument’s value. However, if you reassign a new value to the parameter variable will not affect the argument. To demonstrate this, look at Program 5-10. Program 5-10 (change_me.py) # This program demonstrates what happens when you # change the value of a parameter. def main(): value = 99 print(f'The value is {value}.') change_me(value) print(f'Back in main the value is {value}.') def change_me(arg): print('I am changing the value.') arg = 0 print(f'Now the value is {arg}.') # Call the main function. main() Program Output The value is 99. I am changing the value. Now the value is 0. Back in main the value is 99. Start Animation The main function creates a local variable named value in line 5, assigned the value 99. The statement in line 6 displays 'The value is 99'. The value variable is then passed as an argument to the change_me function in line 7. This means that in the change_me function, the arg parameter will also reference the value 99. This is shown in Figure 5-17. Figure 5-17 The value variable is passed to the change_me function The figure illustrates a variable passed to a function. Line 1: def main open round bracket close round bracket colon at indentation level 0. Line 2: value equals 99 at indentation level 1. Line 3: print open round bracket f single quote The value is open curly braces value close curly braces dot single quote close round bracket at indentation level 1. Line 4: change underscore me open round bracket value close round bracket at indentation level 1. Line 5: print open round bracket f single quote Back in main the value is open curly braces value close curly braces dot single quote close round bracket at indentation level 1. Line 6: def change underscore me open round bracket arg close round bracket colon at indentation level 0. Line 7: print open round bracket single quote I am changing the value dot single quote close round bracket at indentation level 1. Line 8: arg equals 0 at indentation level 1. Line 9: print open round bracket f single quote Now the value is open curly braces arg close curly braces dot single quote close round bracket at indentation level 1. Note: A box contains number 99. An arrow from value and another arrow from arg points to 99. Inside the change_me function, in line 12, the arg parameter is assigned the value 0. This reassignment changes arg, but it does not affect the value variable in main. As shown in Figure 5-18, the two variables now reference different values in memory. The statement in line 13 displays 'Now the value is 0.' and the function ends. Figure 5-18 The value variable is passed to the change_me function The figure illustrates a variable passed to a function. Line 1: def main open round bracket close round bracket colon at indentation level 0. Line 2: value equals 99 at indentation level 1. Line 3: print open round bracket f single quote The value is open curly braces value close curly braces dot single quote close round bracket at indentation level 1. Line 4: change underscore me open round bracket value close round bracket at indentation level 1. Line 5: print open round bracket f single quote Back in main the value is open curly braces value close curly braces dot single quote close round bracket at indentation level 1. Line 6: def change underscore me open round bracket arg close round bracket colon at indentation level 0. Line 7: print open round bracket single quote I am changing the value dot single quote close round bracket at indentation level 1. Line 8: arg equals 0 at indentation level 1. Line 9: print open round bracket f single quote Now the value is open curly braces arg close curly braces dot single quote close round bracket at indentation level 1. Note: A box contains the number 99 and another box contains the number 0. An arrow from value points to 99 and another arrow from arg points to 0. Control of the program then returns to the main function. The next statement to execute is in line 8. This statement displays 'Back in main the value is 99.'. This proves that even though the parameter variable arg was changed in the change_me function, the argument (the value variable in main) was not modified. The form of argument passing that is used in Python, where a function cannot change the value of an argument that was passed to it, is commonly called pass by value. This is a way that one function can communicate with another function. The communication channel works in only one direction, however. The calling function can communicate with the called function, but the called function cannot use the argument to communicate with the calling function. Later in this chapter, you will learn how to write a function that can communicate with the part of the program that called it by returning a value. Self-review This won't affect your score Checkpoint 5.5-4 1 try left When a parameter is changed, it changes the argument that was passed into the parameter as well. True False