Building from Pieces

Parameters and Return Values


Learning Objectives

  • You can distinguish a parameter from an argument.
  • You can define functions with one or more parameters.
  • You can return a value and use it in another expression.
  • You can distinguish printed output from returned values, including None when a function finishes without an explicit return.

The functions in the previous chapter always performed exactly the same work. Parameters let different calls supply different information, and return values let a function hand information back to its caller.

Parameters and Arguments

Consider:

No files opened Select a file to edit

In the definition:

def greet(name):

name is a parameter. It is a name used inside the function.

In the call:

greet("Ada")

"Ada" is an argument. It is the value supplied by this call.

When Python calls a function, it evaluates each argument and gives the resulting value a local parameter name.

For the first call above, local name refers to the string "Ada". For the second call, that call’s local name refers to "Grace".

Each Call Has Its Own Local Names

In this version of greet, the function also gives its message a name. Step through the two calls and watch the state panel. Each call has its own frame, which groups the names belonging to that call.

Code

Step 1 of 12

1 / 12
Formatting...

State

main

No variables

Output

No output yet

The first call has name referring to "Ada" and message referring to "Hello, Ada!". When that call finishes, its frame closes. The second call starts with its own name and creates its own message for "Bob".

The local names from the first call are not reused by the second call.

More Than One Parameter

A function can receive several pieces of information:

def print_session(subject, minutes):
print(f"{subject}: {minutes} minutes")
print_session("Programming", 45)

This call uses positional arguments. Each argument is matched with a parameter by position:

subject → "Programming"
minutes → 45

Order matters. Python cannot know that this call probably reflects a mistake:

print_session(45, "Programming")

Both arguments can still be bound to the two parameter names, although the displayed message no longer makes sense.

Trace how arguments are bound to parameters in several calls:

Now try writing a function’s missing step in natural language. The definition header and both calls are given; write the step that belongs inside the function body.

Write the return step with natural-language programming

0 / 5 points

This exercise combines given blocks with a step you write in natural language. Drag blocks from “Available blocks” into “Program”. First drag the blank block into “Program” to reveal its editable box, then type your step. The editor automatically translates your program into Python; inspect “Generated Python” before submitting.

Define a function called double that takes a number n and returns twice its value without printing inside the function. Use the given definition block and place your written step inside its function body. The function must work for other numbers too, including zero and negative numbers.

Place both given print blocks after the definition, outside the function body: first print the result of double(4), then the result of double(7). The complete program must print these two lines in this order, with no additional output:

8
14

Returning Information

Printing is useful when a function’s job is to communicate with the user. Many functions instead need to produce a value for other code to use. Use return for that:

No files opened Select a file to edit

Step through the same program. Watch when answer gets its value and when output appears.

Code

Step 1 of 6

1 / 6
Formatting...

State

main

No variables

Output

No output yet

The call double(6) evaluates to the returned value 12. It can therefore appear anywhere that value could appear:

print(double(6) + 1)
print(double(double(3)))

The first line prints 13. In the second line, the inner call returns 6, which becomes the argument of the outer call. The outer call returns 12.

Printing and Returning Are Different Jobs

Compare:

def print_double(number):
print(number * 2)
def double(number):
return number * 2

print_double(5) displays 10. By contrast:

result = double(5)

does not display the calculation. It hands 10 back to the caller and stores it in result.

Printing displays information. Returning supplies a value to the caller.

A calculation function is usually more flexible when it returns its result. The caller can then print it, store it, compare it, or use it in another calculation.

A Function Without an Explicit return Returns None

Run this example:

No files opened Select a file to edit

Step through the same program. Compare what is printed with the value assigned to result.

Code

Step 1 of 5

1 / 5
Formatting...

State

main

No variables

Output

No output yet

Every function call evaluates to a value. If execution reaches the end of a function without an explicit return, Python returns the special value None implicitly.

Here the function displayed 14, but the call returned None rather than a calculated number. None is a real Python value commonly used to represent the absence of another useful result. A function can also deliberately write return None; omitting return and explicitly returning None produce the same returned value, although the programmer’s intention may differ.

The next exercises ask you to submit only a function definition. While working, add temporary calls below the definition and run the program to check different arguments. For a calculation function, put the call inside print(...) to see its returned value. Remove the temporary calls before submitting; the grader will make its own calls.

Write a function that uses its parameter in a printed message:

Create a radio badge

0 / 10 points

Define a function named print_badge with one parameter named callsign. The function must print the callsign in this format:

BADGE: Nova

The example above is the output printed by calling print_badge("Nova").

The callsign is a string. Print it exactly as received, preserving any spaces and letter case. An empty callsign produces the prefix BADGE: followed by a newline.

Keep the output inside the function and use the parameter rather than writing Nova directly into the printed text. The function does not calculate a value for its caller, so let it finish without returning another value; its returned value is therefore None. The grader will call your function with several different callsigns. While testing, add calls such as print_badge("Nova") and print_badge("Orbit") below the definition and run the program. Remove those temporary calls before submitting, so the submission contains only the function definition.

Trace displayed and returned values:

Then write a function that calculates and returns a result from two arguments:

Estimate a delivery route

0 / 15 points

Define a function named route_cost with two parameters: distance and cost_per_km.

Return the route’s cost, calculated as distance * cost_per_km. Do not print the result inside the function. For example, route_cost(12, 1.5) must return 18.0.

Both arguments are non-negative numbers. They may be whole numbers or decimals, and either argument may be zero. Return the ordinary multiplication result without rounding it.

To test the function, temporarily add calls inside print(...), such as print(route_cost(1.5, 1.5)), which should display 2.25. Try several arguments, then remove the temporary calls before submitting. The submission should contain only the function definition and should not read input; the grader will call it with different whole-number and decimal arguments.

return Ends the Current Call

When Python executes return, the current function call ends immediately:

def describe_temperature(temperature):
if temperature < 0:
return "freezing"
if temperature < 15:
return "cold"
return "mild or warm"

With -5, the first return ends the call. The later conditions are not evaluated. Chapter 5 applies this rule carefully inside loops.

Trace a call to another function with more than one return statement:

Follow a classification call

0 / 3 points

What does this program print?

def classify(number):
if number < 0:
return "low"
return "ok"
print(classify(-3))

Finish by explaining how printed output and returned values follow different paths:

Explain two kinds of function outcome

0 / 10 points

Explain in plain language what happens in this program:

def show_square(number):
print(number * number)
def square(number):
return number * number
shown = show_square(4)
calculated = square(4)
print(shown)
print(calculated)

In four or five sentences, explain what each call displays or returns, what is stored in shown and calculated, and why the complete output contains None.

Check Your Understanding

  1. How does a parameter differ from an argument?
  2. How are positional arguments matched to parameters?
  3. How can the caller use a function’s returned value?
  4. What value does a call produce if the function prints a message but has no explicit return?
  5. What happens to the rest of a function’s body when a return statement runs?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0