Lesson 8: Creating Functions with Parameters

Overview

In this lesson, students practice using and creating functions with parameters. Students learn that writing functions with parameters can generalize solutions to problems even further. Especially in situations where feel like you are about to duplicate some code with only a few changes to some numbers, that is a good time to write a function that accepts parameters. In the second half of the lesson, students make a series of modifications to a program that creates an “Under the Sea” scene by adding parameters to functions to more easily add variation to the scene. Lastly, students are introduced to App Lab’s random number functions to supply random values to function calls so the scene looks a little different every time the program runs.

Purpose

Writing functions with parameters is a simple idea, but it traditionally has some devilish details for new learners of programming. The basic idea is that you often want to write a function that takes some input and performs some action based on that input. For example, the turtle function moveForward is much more useful when you can specify how much to move forward (e.g., moveForward(100)), rather than just a fixed amount every time. It’s very common to encounter situations where as a programmer you realize that you basically need a duplicate of some code you’ve already got, but you just want to change some numbers. That’s a good time to write a function with a parameter; the parameter just acts as a placeholder for some value that you plug in at the time you call the function. Just like it’s considered good practice to give descriptive names to your functions, the same is true for the names of the parameters themselves. For example: drawSquare(sideLength) is better than drawSquare(stuff).

Agenda

Warm Up (5 mins)

Activity (40 mins)

Wrap Up (5 min)

Assessment

Extended Learning

View on Code Studio

Objectives

Students will be able to:

  • Write functions with parameters to generalize a solution instead of duplicating code.
  • Identify appropriate situations for creating a function with parameters.
  • Use random numbers as inputs to function calls for the purpose of testing.
  • Add parameters to a function in an existing piece of code to generalize its behavior.

Preparation

  • Review functions in the "Debug Commands" toolbox located in App Lab to assist in debugging code. These functions are to the left of the Debug Console.

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Students

Vocabulary

  • Parameter - An extra piece of information passed to a function to customize it for a specific need

Introduced Code

Teaching Guide

Warm Up (5 mins)

Recall the Purpose of Parameters

Discussion Goal

We want to get back to programming fairly quickly.

Use the Getting Started Activity to briefly recall the benefits of functions with parameters they have already seen and motivate the desire to create them for themselves.

Students will make their own functions with parameters in this lesson.

Remarks

In the previous lesson, we learned to use a lot of new turtle commands. Some of these commands accept a parameter, or even many parameters, which allow us to pass values to the function. This allowed us to make much more interesting images by specifying precisely how far the turtle should move or turn, and introduced the ability to choose specific pen sizes and colors.

Parameters are a powerful programming construct.

  • Suppose we have a whole group of similar problems, like turning the turtle some amount.
  • Without a parameter we would need 360 different functions, one for each number of degrees we wanted to turn!
  • Parameters allow us to use a single function as a general solution to a whole group of problems.

This is clearly a useful construct to use in our programs, and in today’s lesson we’re going to learn how to create functions with parameters for ourselves.

Activity (40 mins)

Transition to Code Studio

Writing Functions with Parameters: Under the Sea

The levels in Code Studio for this lesson walk students through a number of small exercises that build up to making a small "under the sea" drawing.

Below is a quick reference guide that shows what students are asked to do in each level.

Wrap Up (5 min)

When do you need a function with a parameter?

Discussion Goal

Having used parameters to generalize the behavior of many functions, students should attempt to formalize their understanding of what parameters are and why they are beneficial. Important points to draw out are:

  • Parameters allow the creation of a generalized solution to a whole class of problems, rather than individually solving many specific problems.
  • Parameters remove the need to create repetitive functions, making code easier to write, read, and change.

Reflection: Students should briefly journal and share responses to the following question:

Prompt: "Develop a rule for deciding when to create a function with a parameter rather than a normal function. Below your rule write a couple sentences justifying your rule."

Share Responses:

Once students have written their responses, have them share with a neighbor and ask a few students to share their rules with the class. Focus in particular on the reasons for creating a function with a parameter, as students will likely hit on the two points above. For example:

  • “Whenever you have two functions that basically do the same thing make a function with a parameter instead, to remove the need to duplicate code.”
  • “If you need a function to do the same thing a lot of different ways, then use a parameter so one function can do it right away.”

If these ideas don’t come out, then you may make these points yourself and instead ask students where they saw these principles in today’s activities. Point out that every time they added a parameter to a function, they generalized the behavior of the function without having to rewrite the code.

Assessment

  1. Multiple Choice: Which of the following are true?
    • Functions with parameters can be used to prevent the creation of duplicated code.
    • Parameters can only be used once within the body of a function.
    • Parameters generalize the solution of a specific problem.
    • Parameters need not be provided to a function in any particular order.
  2. Free Response: “Abstraction” is often used to indicate cases where we focus on a general case and ignore a specific instance of a problem. Given this meaning of the word, how are functions with parameters an example of abstraction?

Extended Learning

Students can extend their digital scene by creating parameterized functions for other components of the scene or adding additional parameters to their current set of functions.

  • Functions with Parameters
  • 2
  • (click tabs to see student view)
  • Drawing Shapes With Parameters
  • 3
  • 4
  • 5
  • 6
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Defining and Using a Function with a Parameter

From the video, you learned that defining multiple functions to draw different sized squares results in lots of repetitive functions - they are essentially the same, with a few numbers changed - and this is not desirable. Any time you find yourself effectively copy and pasting large sections of code, it's usually a sign that there is a better way.

Do This:

Uh oh! Something's wrong! We've set up a program that runs, but doesn't do what it's supposed to do. The program is supposed to make a drawing with two squares that looks like this:

We've given you the drawSquare(size)function that was created in the video, but it's not quite right. Fix the code inside the drawSquare function so that the program creates the drawing correctly.

HINT: You should only need to change one thing about an existing line of code. You don't need to add or remove any lines of code. Remember: The parameter size acts like a placeholder for a value that gets plugged into each call to moveForward().

View on Code Studio

Student Instructions

Defining Functions with Parameters

This time you're going to write your own function with parameters to complete an image. Two function calls to drawTriangle have been placed at the top of the program but the function itself needs to be defined. The program should draw this:

Do This:

Complete the function definition for drawTriangle(sideLength) . Notice that you have already been given a descriptive and meaningful parameter name, sideLength, but you can change it if you wish.

Hint: you should put the pen down and pick it up as part of the definition of drawTriangle - that way you guarantee that a call to drawTriangle will always actually draw. Picking the pen up as the last act of the function is a nice thing to do for any other code that might not be expecting drawTriangle to have a side effect of putting the pen down.

As a reminder of how to use a parameter within the function here is a correct version of drawSquare(size) for reference.

View on Code Studio

Student Instructions

Calling Functions with Multiple Parameters

You're about to see a new definition for drawSquare that has two parameters: drawSquare(size, borderWidth) Notice how multiple parameters are separated by commas.

Do This:

Add to the code to make two calls to the new two-parameter version of drawSquare to make an image similar to this one.

View on Code Studio

Teaching Tip

Potential stop/recap point

You might consider having students work up to this level and then stopping to review it as a whole class.

This task is challenging and represents the crux of the whole parameters "thing". It's worth the time to get this level right and to explain the terminology and what's happening.

Student Instructions

Defining Functions with Multiple Parameters

Now it's your turn to define a function that accepts multiple parameters. Just like in the previous example make sure you separate your parameters with commas and give them descriptive and meaningful names.

Do This:

  • Drag out the function block, and name your function drawTriangle.
  • Define drawTriangle to have two parameters within the parentheses making sure to give them descriptive and meaningful names separated by commas.
  • The example below uses size and width for parameter names but you can use whatever you like.

  • Then write the code inside function drawTriangle(size, width) that will make it work as described.
  • Test it out! Run the code and experiment to create an image similar to the one below.

  • Check Your Understanding: Defining Functions
  • 7
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

In creating a function you might define the names of the funciton's parameters but they don't get values until you call the function.

Here is an example of identifying (defining) the function's parameters:

function drawShape(size, color)

versus giving the parameters a value (calling):

drawShape(150, "red")

Student Instructions

View on Code Studio

What are "Comments" in code?

You will begin to see code that has a new type of block in it that looks like this:

A "Comment" block doesn't do anything when you run the code. It is simply a way to leave notes in code.

Programmers write comments into their code for two main reasons:

  1. sharing code with other programmers
  2. remembering their own thoughts or plans for code they write.

For both cases a programmers write comments into their code to explain their thinking to a human reader. Writing your own comments is a skill you'll develop over time.

Click continue to see how to add your own comments, or keep reading below about how and why to write comments.

Continue







Why write comments?

For others - collaborating:

When sharing code with others, comments are useful to point out sections of code you might want help with, or to explain a complicated section of code that's hard to reason about. It's useful for example to write a comment like:

Block version Text version

because it helps the reader understand when, where, why that section of code might be executed.

For yourself

When writing comments for yourself, it might be a note about how you plan to solve a problem, or jotting down the reason you did something to remind yourself later when you come back to it. For example you might write a comment like:

For planning

Many programmers, when starting from scratch, like to write out a high level plan for the code they want to write in comments, and then go in starting writing code to fill in the plan. This is particularly useful if you're facing a large problem that needs to be broken down into parts. A plan for drawing an under the sea scene might look like this:

Once you have written out a strategy in comments you'll be able to remember the big picture, after you inevitably run into lots of sub-problems that require your time and brain to solve, or debug.

View on Code Studio

Validation note: no code is checked on this level. There is no automatic way to check whether a student has added a particular comment into the code.

View on Code Studio

Now you try it - Add a comment

The starting code provided has some comments already in it.

Do This

Insert a comment that says Draw all the starfish just above the first call to drawStarfish().

  • The Comment block is in the Functions toolbox (Show me)
  • See how: expandable

Click finish once you've added the comment. And keep adding comments as you

View on Code Studio

Student Instructions

Under the Sea!

In the next several challenges you will be working to improve one program that draws an underwater scene. Each time you finish a puzzle and move on to the next one, your code will be pulled forward and you'll get new instructions telling you what to add.

Do This:

  • Read through the program provided to get a basic understanding of what it does.
  • Add function calls in the early lines of the program (somewhere after the background is drawn) so that two fish, two starfish, and two pieces of seagrass appear somewhere in the scene. You don't need to provide values for the parameters at this stage.
  • Hint: you need to call moveTo before drawing a second fish, starfish or seagrass, otherwise you won't see the second one because it will draw exactly over the first one -- those functions draw based on where the turtle is just before the call.
  • Test out your code. If something doesn’t work like you expect, consider whether you can add anything to the functions’ definitions to make them better.
  • Continue to the next level, where your code will be waiting for you.

View on Code Studio

Student Instructions

Adding Parameters to Functions: drawStarfish

We want to make our picture more interesting by adding some variety. Currently the drawStarfish function can only draw a starfish of size 60.

Add a parameter to the function definition for drawStarfish that allows you to control its size - like drawStarfish(size). Make sure your parameter has a descriptive and meaningful name.

Update your function calls to use your new version of drawStarfish and change the size of your starfish.

View on Code Studio

Student Instructions

Adding Parameters to Functions: drawSeagrass

To keep adding variety to our image let's keep adding parameters to our functions. Currently the drawSeagrass function can only draw a piece of seagrass with arcs of radius 100.

Add a parameter to the function definition for drawSeagrass that allows you to control its size. (You'll only need to change the radius of each arc.) Make sure your parameter has a descriptive and meaningful name.

Update your function calls to use your new version of drawSeagrass and change the size of the seagrass in your image.

View on Code Studio

Student Instructions

Adding parameters to functions: drawFish

Let's update our drawFish function to accept a parameter. Currently drawFish can only draw a fish of size 30.

Add a parameter to the function definition for drawFish that allows you to control its size (Note: the pen width is important here.) Make sure your parameter has a descriptive and meaningful name.

Update your function calls to use your new version of drawFish and change the size of the fish in your image.

View on Code Studio

Student Instructions

Multiple Parameters

Let's make our drawings even more interesting by adding some variety to the color.

Add three more parameters called red , green , and blue to your function definition for drawFish which allow you to set the color of the fish when you call the function. Remember to separate them with commas!

Note: this means that drawFish will now have 4 parameters total: size, red, green, and blue.

HINT: inside drawFish just replace the numbers of the penRGB values with the parameters of your function.

Change the function calls at the top your code to draw different colored fish.

View on Code Studio

Teaching Tip

Validation note: here we only check to see if randomNumber(min,max) is used as a parameter in calls to the functions.

Student Instructions

Random Input

You have a new block that allows you to generate a random number. You can use this instead of hard-coding in values every time you call a function.

Read the documentation for the randomNumber block.

Do This

Use randomNumber to provide random input to all three of your drawing functions. Just insert the call to randomNumber where you would otherwise put numbers.

Like this:

Use randomNumber in calls to all three of your drawing functions:

  • drawStarfish
  • drawSeagrass
  • drawFish

This is a great way to test out functions and also get some interesting looking images. Every time you run the program you can get slightly different looking scenes like the ones below.

  • Check Your Understanding: Using Random Numbers
  • 16
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

The answer gets at the difference between defining a function's parameters and calling that function. Since randomNumber returns a value (a number) it can be used in places where you would otherwise provide a numeric value.

For example, you don't define a function with a numeric parameter. This doesn't make sense:

function drawShape(50){ ... } <-- don't do this.

Instead you define the function with a named parameter like so:

function drawShape(size){ ... }

and then call it, supplying a value for that parameter like so:

drawShape(50);

In the case of this question we're using randomNumber in place of that value for the function call.

drawShape( randomNumber(25,75) );

Student Instructions

Consider these various uses of randomNumber. Each answer describes the use and shows a code example. Which one of the following is NOT a valid use of randomNumber

  • Challenge: Continue Your Drawing With More Functions
  • 17
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Validation note: we don't check to see if the student actually drew an under-the-sea scene.

To promote free play here we've reduced what we check to a bare minimum only to ensure the student doesn't have a blank project. We check that the student:

  • has at least one call to each of the draw functions: drawFish, drawSeagrass, drawStarFish
  • uses randomNumber(min,max) at least 3 times in the program.

Student Instructions

Keep Going!

At this point you've seen how parameters can help generalize the behavior of a function to perform a variety of tasks, not just one. This will prove to be a very useful skill as we continue to develop as programmers.

For now, keep adding to your drawing. Make more function calls and see if you can continue to use random numbers to add variety to your drawings.

  • AP Practice Response - Managing Complexity
  • 18
  • (click tabs to see student view)
View on Code Studio

Student Instructions

AP Practice - Performance Task Response

The AP Create Performance task asks you to write about an abstraction that you developed and wrote into your code. Most of the time that means identifying a function or procedure you wrote to help "manage complexity" in your program.

Here is the actual prompt from the Create Performance Task:

2d. Capture and paste a program code segment that contains an abstraction you developed individually on your own (marked with a rectangle). This abstraction must integrate mathematical and logical concepts. Explain how your abstraction helped manage the complexity of your program.
(Must not exceed 200 words)


Below is a segment of code from an "under the sea" program with a rectangle drawn around a portion of the code identifying an abstraction. Imagine that you wrote this and are composing an AP response about how this abstraction manages complexity. (Note: ignore the requirement that the abstraction integrate "mathematical and logical concepts" for this practice response. Just write about managing complexity).

Explain how the abstraction marked with the rectangle in the code above helps manage complexity of this program.

  • Check Your Understanding
  • 19
  • 20
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Correct answers:

  • Functions with parameters can be used to prevent the creation of duplicated code.
    • Explanation: For example, consider the case where we want to turn the turtle 180 degrees. Using turnLeft() (without parameters), we'd have to call the turn function twice in a row to achieve the desired results. But by using the turn function with parameters (e.g. turnLeft(180), we can consolidate this action into a single line of code.
  • Parameters help generalize the solution of a specific problem.
    • Explanation: A function defined with parameters solves the general case of a particular problem or task. The parameters act as placeholders for whatever data the programmer passes into the function when it gets called. It isn't until a function is actually called within a program that a specific instance of the problem is solved.

Incorrect answers:

  • Parameters can only be used once within the body of a function.
  • Values do not need to be provided to a function with parameters in any particular order.
    • Explanation: When calling a function with parameters in your program, you must pass the corresponding values into the function in the same order as they are listed in the function definition.

Student Instructions

View on Code Studio

Student Instructions

“Abstraction” is often used to focus on a general case and ignore a specific instance of a problem.

Given this meaning of the word, how are functions with parameters an example of abstraction?

Standards Alignment

View full course alignment

Computer Science Principles

2.2 - Multiple levels of abstraction are used to write programs or create other computational artifacts
2.2.1 - Develop an abstraction when writing a program or creating other computational artifacts. [P2]
  • 2.2.1C - An abstraction generalizes functionality with input parameters that allow software reuse.
2.2.2 - Use multiple levels of abstraction to write programs. [P3]
  • 2.2.2A - Software is developed using multiple levels of abstractions, such as constants, expressions, statements, procedures, and libraries.
  • 2.2.2B - Being aware of and using multiple levels of abstraction in developing programs helps to more effectively apply available resources and tools to solve problems.
5.3 - Programming is facilitated by appropriate abstractions.
5.3.1 - Use abstraction to manage complexity in programs. [P3]
  • 5.3.1A - Procedures are reusable programming abstractions.
  • 5.3.1C - Procedures reduce the complexity of writing and maintaining programs.
  • 5.3.1D - Procedures have names and may have parameters and return values.
  • 5.3.1F - Parameters generalize a solution by allowing a function to be used instead of duplicated code
  • 5.3.1G - Parameters provide different values as input to procedures when they are called in a program.
  • 5.3.1L - Using lists and procedures as abstractions in programming can result in programs that are easier to develop and maintain.
5.4 - Programs are developed, maintained, and used by people for different purposes.
5.4.1 - Evaluate the correctness of a program. [P4]
  • 5.4.1C - Meaningful names for variables and procedures help people better understand programs.
  • 5.4.1D - Longer code blocks are harder to reason about than shorter code blocks in a program.
  • 5.4.1E - Locating and correcting errors in a program is called debugging the program.
  • 5.4.1F - Knowledge of what a program is supposed to do is required in order to find most program errors.
  • 5.4.1G - Examples of intended behavior on specific inputs help people understand what a program is supposed to do.
  • 5.4.1H - Visual displays (or different modalities) of program state can help in finding errors.
  • 5.4.1I - Programmers justify and explain a program’s correctness.
  • 5.4.1J - Justification can include a written explanation about how a program meets its specifications.
  • 5.4.1K - Correctness of a program depends on correctness of program components, including code blocks and procedures.

CSTA K-12 Computer Science Standards (2017)

AP - Algorithms & Programming
  • 2-AP-14 - Create procedures with parameters to organize code and make it easier to reuse.
  • 3A-AP-17 - Decompose problems into smaller components through systematic analysis, using constructs such as procedures, modules, and/or objects.
  • 3A-AP-18 - Create artifacts by using procedures within a program, combinations of data and procedures, or independent but interrelated programs.
  • 3B-AP-14 - Construct solutions to problems using student-created components, such as procedures, modules and/or objects.