MGU Computer Science Series — Programming with Python
Part III: Functions and Program Design
Parameters · Arguments · Return Values · Function Interfaces
Chapter 12 of 30
12
MGU Computer Science Series  ·  Programming with Python  ·  Library Textbook Edition

Chapter 12:
Parameters, Arguments,
and Return Values

How functions receive information from the outside world, and how they send results back — including the most important distinction in beginner Python programming: printing versus returning

■ Part III of VII ■

■ 10 Sections  •  Chapter 12 of 30 ■

Builds on Chapter 11 — Defining and Calling Functions

Chapter Introduction and Learning Objectives

Chapter 11 introduced functions as named, reusable blocks of code. You learned how to define a function, how to call it, and how execution jumps into a function and returns when it finishes. But those early functions had a significant limitation: they always did exactly the same thing every time. They could not adapt to different situations, work with different values, or hand a result back to the rest of the program.

This chapter removes that limitation. You will learn how to give information to a function using parameters and arguments. You will learn how functions send results back using return values. You will learn one of the most important distinctions in beginner Python programming: the difference between printing a result and returning a result. And you will learn how to design function interfaces that are clear, reusable, and easy to test.

Why This Chapter Matters

These ideas are foundational. Everything that follows in this textbook — data structures, files, classes, and projects — depends on writing functions that receive information and return results correctly. Confusing print() with return is one of the most common bugs beginning programmers write, and it is also one of the easiest to fix once you understand the difference clearly.

10Sections
10Objectives
10Key Terms
30Total Chapters

Learning Objectives

By the end of this chapter, you should be able to:

  1. 1Explain why functions are more useful when they receive information rather than relying on fixed values.
  2. 2Define parameter and argument, and explain how arguments are matched to parameters by position.
  3. 3Write and call functions with multiple parameters, supplying the correct number of arguments.
  4. 4Use the return statement to send a value back to the calling code.
  5. 5Explain the difference between printing a value and returning a value, and identify which a given function should do.
  6. 6Use a function's return value inside expressions, assignments, and other function calls.
  7. 7Explain what None is, when a function returns it, and why that can cause errors.
  8. 8Write functions with default parameter values and explain the rules governing where defaults may appear.
  9. 9Design a function interface — name, parameters, and return value — for a clearly stated task.
  10. 10Trace function calls by hand, tracking parameter values, computed values, and returned results.

Sections at a Glance

Sections 12.1 – 12.4
Getting Information Into Functions
Parameters · Arguments · Positional Matching · Multiple Parameters

Giving Information to Functions

Imagine you want a function that calculates the area of a rectangle. A rectangle's area is its width multiplied by its height.

Here is a version of that function that does not receive any information:

def calculate_area(): width = 5 height = 3 area = width * height print(area)

This function works, but it always calculates the area of a rectangle that is exactly 5 units wide and 3 units tall. It cannot calculate the area of any other rectangle. To calculate a different area, you would have to rewrite the function or write a new one.

That defeats the purpose of writing a function.

The solution is to design the function so that the width and height are supplied by whoever calls it. The function should work for any width and any height, not just specific values baked into the function body.

This is what parameters are for.

def calculate_area(width, height): area = width * height print(area)

Now the function receives the width and height from outside. Every time you call it, you can supply different values. The function does the same calculation every time, but it works on whatever values it receives.

Core Idea

Functions are more useful when they receive the information they need rather than assuming fixed values. A function with parameters can solve a whole family of problems, not just one specific case.

Parameters

A parameter is a variable that appears inside a function's definition. It acts as a placeholder for a value that will be supplied when the function is called.

Parameters are listed inside the parentheses of the def line, separated by commas.

def greet(name): print("Hello,", name)

In this function, name is a parameter. It is a variable that does not exist yet when the function is defined. It will receive a value only when the function is called.

A function can have more than one parameter:

def describe_pet(animal, pet_name): print("I have a", animal, "named", pet_name)

Here animal and pet_name are two parameters. Both receive values when the function is called.

Key Points
What you need to remember about parameters
  • LocationParameters are defined inside the parentheses on the def line.
  • ScopeParameters are local variables. They only exist inside the function.
  • CountA function can have zero, one, or many parameters.
  • SourceParameters receive their values from arguments when the function is called.

Parameters are not yet real values when you write the function definition. They are named slots. The real values arrive from outside, at the moment of the function call.

Arguments

An argument is the actual value that is passed into a function when you call it. Arguments fill the parameter slots.

greet("Maria")

Here, "Maria" is the argument. When the function call executes, name receives the value "Maria". From that point on, inside the function, name is "Maria".

describe_pet("cat", "Luna")

Here, "cat" is the argument for animal and "Luna" is the argument for pet_name.

Arguments are matched to parameters by position. The first argument goes to the first parameter, the second argument to the second parameter, and so on.

def calculate_area(width, height): area = width * height print(area) calculate_area(10, 4)

When this runs:

  • width receives 10
  • height receives 4
  • area becomes 40
  • The function prints 40

If you reverse the arguments, the parameters receive different values:

calculate_area(4, 10)

For calculate_area, the result is the same because multiplication is commutative. But for other functions — such as one that calculates a price after discount — the order matters significantly. Be careful to supply arguments in the correct order.

TermWhere It AppearsWhat It Is
ParameterFunction definition (def line)A placeholder variable
ArgumentFunction callThe actual value supplied

Multiple Parameters

Functions can accept multiple parameters. Each parameter is a separate variable inside the function, and each receives a corresponding argument.

def calculate_total(price, quantity, tax_rate): subtotal = price * quantity tax = subtotal * tax_rate total = subtotal + tax print(total) calculate_total(12.99, 3, 0.08)

Tracing this call:

  • price receives 12.99
  • quantity receives 3
  • tax_rate receives 0.08
  • subtotal becomes 38.97
  • tax becomes 3.1176
  • total becomes 42.0876
  • The function prints 42.0876

You must supply exactly the right number of arguments. If a function has three parameters and you call it with two arguments, Python raises a TypeError:

calculate_total(12.99, 3)
TypeErrorTypeError: calculate_total() missing 1 required positional argument: 'tax_rate'

The error message is informative. It tells you which argument is missing. Read error messages carefully — they are your first debugging tool.

Similarly, supplying too many arguments is also an error:

calculate_total(12.99, 3, 0.08, "extra")
TypeErrorTypeError: calculate_total() takes 3 positional arguments but 4 were given
Worked Example
A function with three parameters
def describe_trip(destination, distance_km, days): print("Destination:", destination) print("Distance:", distance_km, "km") print("Trip length:", days, "days") print("Average per day:", distance_km / days, "km") describe_trip("Oslo", 480, 3)
OutputDestination: Oslo Distance: 480 km Trip length: 3 days Average per day: 160.0 km

The function works for any destination, distance, and number of days. Try calling it with different arguments.

Sections 12.5 – 12.8
Getting Results Back Out of Functions
Return Values · Printing vs. Returning · Expressions · None

Return Values

So far, every function in this chapter has displayed its result using print(). That works for showing information to a user, but it has a serious limitation: the result vanishes after it is printed. No other part of the program can use it.

Consider this function:

def calculate_area(width, height): area = width * height print(area)

If you call calculate_area(10, 4), it prints 40. But what if you want to use that area in a larger calculation — say, to figure out the cost of flooring at a certain price per square unit? You cannot, because the value 40 was only printed, not stored or passed anywhere.

The solution is for the function to return its result.

The return statement sends a value back to wherever the function was called. The calling code can then store it, use it in an expression, print it, or pass it to another function.

def calculate_area(width, height): area = width * height return area

Now when you call this function, it produces a value that the rest of the program can use:

room_area = calculate_area(10, 4) print("Area:", room_area)
OutputArea: 40

You can also use the returned value directly in an expression:

price_per_unit = 3.50 total_cost = calculate_area(10, 4) * price_per_unit print("Total cost:", total_cost)
OutputTotal cost: 140.0
What return Does

1. It sends a value back to the calling code.

2. It immediately ends the function's execution.

Any code written after a return statement in the same function will not run:

def calculate_area(width, height): area = width * height return area print("This line never runs.") # unreachable code

The return statement is one of the most important tools in function design. Learn to use it consistently.

Printing Versus Returning

One of the most common mistakes beginners make is confusing print() and return. This section explains the difference clearly and directly.

The Core Distinction

print() displays a value on the screen. That is all it does. The value is shown to the user, and then it is gone. No other part of the program can work with it further. return sends a value back to the calling code. The calling code can store it, use it, pass it forward, or print it. The value lives on.

Here are two versions of the same function. Read them carefully:

Version A — Prints the Result
def double(number): print(number * 2)
Version B — Returns the Result
def double(number): return number * 2

Now watch what happens when you try to use the result:

result = double(5) print(result)

With Version A:

  • double(5) runs and prints 10 to the screen immediately.
  • The function returns None (nothing).
  • result receives None.
  • The print(result) line prints None.
Output (Version A)10 None

With Version B:

  • double(5) runs silently.
  • The function returns 10.
  • result receives 10.
  • The print(result) line prints 10.
Output (Version B)10

The difference matters enormously when you want to use a function's result in further calculations, store it in a list, write it to a file, or pass it to another function. A function that only prints cannot do any of those things. A function that returns can.

General Rule

If a function computes a value that the rest of the program needs, use return. Use print() only when the function's specific job is to display information. A practical test: ask yourself, "Does the rest of my program need this value?" If yes, use return. If the function's only job is to show something to the user, print() is appropriate — but even then, it is often cleaner to return the value and let the calling code decide whether to print it.

Tracing Exercise
Trace this carefully before reading the answer
def add(a, b): return a + b def show_sum(x, y): print(x + y) total = add(3, 7) print(total) result = show_sum(3, 7) print(result)
Output10 10 None
  • add(3, 7)Returns 10. total is 10. print(total) prints 10.
  • show_sum(3, 7)Prints 10 immediately. It returns None. result is None. print(result) prints None.

Using Function Results in Expressions

When a function returns a value, that value can be used anywhere an expression is valid. You can use it in arithmetic, comparisons, assignments, other function calls, or print statements.

def square(n): return n * n print(square(5)) # prints 25 print(square(3) + square(4)) # prints 25 (the Pythagorean triple) total = square(10) + square(2) print(total) # prints 104

You can also pass the result of one function directly as an argument to another:

def double(n): return n * 2 def square(n): return n * n print(square(double(3))) # double(3) returns 6, square(6) returns 36
Execution Trace
square(double(3))
  • Step 1double(3) is called. Returns 6.
  • Step 2square(6) is called with 6. Returns 36.
  • Step 3print(36) prints 36.

This kind of composition — using the result of one function as the argument to another — is a powerful and natural pattern in Python. Keep it simple and readable. If a chain of function calls becomes hard to read, break it into separate assignment steps.

Harder to Read
print(square(double(int(input("Enter a number: ")))))
Easier to Read
raw = input("Enter a number: ") number = int(raw) doubled = double(number) result = square(doubled) print(result)
Style Note

Clarity is more valuable than compactness, especially while you are learning.

None and Missing Return Values

In Python, every function call produces a value. If a function does not have a return statement, or if execution reaches the end of the function without hitting return, the function automatically returns a special value called None.

None represents the absence of a value. It is not zero, not an empty string, not False. It is its own type, called NoneType.

def greet(name): print("Hello,", name) result = greet("Sam") print(result)
OutputHello, Sam None

greet does not have a return statement, so it returns None. When you assign the result of a call to greet to a variable, that variable holds None.

This is often a source of bugs. A common mistake looks like this:

def calculate_tip(bill_amount, rate): tip = bill_amount * rate print(tip) # prints, but does not return tip_amount = calculate_tip(45.00, 0.18) total = 45.00 + tip_amount # TypeError
TypeErrorTypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

The programmer printed the tip but forgot to return it. When the code tries to add tip_amount to the bill, it gets a TypeError because tip_amount is None, not a number.

The Fix

Replace print(tip) with return tip.

Checking for None: you can check whether a variable holds None using is None:

result = greet("Sam") if result is None: print("The function returned nothing.")
Use is None, Not == None

The is operator checks identity, which is the correct way to test for None in Python.

Summary

Functions without return produce None.

Functions that hit a bare return with no value also produce None.

Storing or using None where a number or string is expected causes errors.

Always check whether your function is supposed to return something, and if so, make sure it does.

Sections 12.9 – 12.10
Designing Functions People Can Use Well
Default Parameters · Function Interfaces · Design Practice

Default Parameters at an Introductory Level

Sometimes a function has a parameter that usually takes the same value, but occasionally needs a different one. Python lets you assign a default value to a parameter. If the caller does not supply that argument, the default is used automatically.

def greet(name, greeting="Hello"): print(greeting + ",", name)

This function has two parameters: name and greeting. The parameter greeting has a default value of "Hello".

You can call it with one argument:

greet("Maria")
OutputHello, Maria

Or with two arguments to override the default:

greet("Maria", "Good morning")
OutputGood morning, Maria

Default parameters make functions more flexible without requiring callers to always supply every detail.

Another Example
A tip calculator with a default rate
def calculate_tip(bill_amount, rate=0.18): tip = bill_amount * rate return tip print(calculate_tip(50.00)) # uses default rate of 18% print(calculate_tip(50.00, 0.20)) # caller specifies 20%
Output9.0 10.0
Rules for Default Parameters

Default parameters must come after non-default parameters in the function definition.

This is valid: def f(a, b=10):

This is a SyntaxError: def f(a=10, b): — you cannot have a required parameter after a default parameter.

Default parameters are useful for optional settings, standard rates, default messages, and any case where one value makes sense for most callers but the function should still accept alternatives.

You do not need to use default parameters in every function. Apply them when they genuinely make a function easier to use without hiding important decisions.

Designing Useful Function Interfaces

A function's interface is the combination of its name, its parameters, and its return value. The interface is what other parts of the program see and use. The body is the hidden implementation.

A well-designed function interface has these qualities:

Quality 1
A Clear Name
The name describes what the function does. Good names are clear and readable: calculate_area, is_valid_password, get_average, format_name. Avoid vague names like do_stuff, helper, or process.
Quality 2
Necessary Parameters Only
The parameters represent the information the function genuinely needs. Give the function exactly what it needs to do its job, and no more.
Quality 3
A Useful Return Value
The return value is the result the rest of the program needs. If the function computes something, return it. Let the caller decide whether to print it, store it, or use it further.
Quality 4
One Job, Done Well
A function called get_and_print_and_save_the_total is trying to do too much. Separate concerns into separate functions.
Worked Example
Designing a function from scratch
  • TaskWrite a function that takes a student's score and the maximum possible score, and returns the percentage as a float.
  • Step 1Identify the inputs: score and maximum.
  • Step 2Identify the output: the percentage as a float.
  • Step 3Name the function: calculate_percentage is clear and specific.
def calculate_percentage(score, maximum): percentage = (score / maximum) * 100 return percentage

Step 5 — Test it:

pct = calculate_percentage(38, 50) print(pct) # should print 76.0 pct = calculate_percentage(100, 100) print(pct) # should print 100.0 pct = calculate_percentage(0, 50) print(pct) # should print 0.0

This function is short, clear, and testable. It does one thing. It returns its result. It does not print anything. The caller decides what to do with the percentage.

Common Interface Design Mistakes

Mixing computing and printing in the same function makes the function harder to reuse:

Hard to Reuse — Prints, Cannot Be Used Further
def calculate_percentage(score, maximum): percentage = (score / maximum) * 100 print(f"Your score: {percentage:.1f}%")

Hard-coding values that should be parameters locks the function into one specific case:

Only Works for Scores Out of 100
def calculate_percentage(score): percentage = (score / 100) * 100 return percentage
Watch Out

Taking too many parameters makes a function hard to call correctly. If you find yourself writing a function with five or more parameters, consider whether it should be broken into smaller functions.

Good function design is a skill that develops with practice. Start simple. Keep functions small. Return values rather than printing them. Test each function separately before combining them.

Chapter Summary

Key Terms

parameter
A variable defined in a function's def line that acts as a placeholder for information the function will receive when called.
argument
The actual value passed to a function in a function call. Arguments fill parameter slots by position.
positional argument
An argument whose value is assigned to a parameter based on its position in the call.
return value
The value a function sends back to the calling code using the return statement.
return statement
A Python statement that ends a function immediately and sends a value back to the caller.
None
A special Python value representing the absence of a value. Functions without a return statement return None automatically.
NoneType
The type of None. When None is used where a number or string is expected, Python raises a TypeError.
default parameter
A parameter that has a preset value, used when the caller does not supply that argument.
function interface
The combination of a function's name, its parameters, and its return value — the "contract" between the function and the rest of the program.
composition
Using the return value of one function as an argument to another function.
unreachable code
Code that appears after a return statement in a function body and can never execute.
PracticeCode Reading

Read each function carefully. Do not run the code yet. Answer the questions based on your reading.

Exercise 1
def multiply(a, b): return a * b
  1. How many parameters does this function have?
  2. What does it return?
  3. Write a function call that passes 6 and 7 as arguments.
  4. What value would the function return for that call?
Exercise 2
def format_greeting(name, title="Ms."): return "Good morning, " + title + " " + name + "."
  1. Which parameter has a default value?
  2. What does format_greeting("Patel") produce?
  3. What does format_greeting("Patel", "Dr.") produce?
  4. Could you call this function with zero arguments? Explain.
Exercise 3
def compute(x, y): result = x + y print(result) total = compute(8, 5) print(total)
  1. Does compute return a value?
  2. What is printed by compute(8, 5) itself?
  3. What does total hold after the assignment?
  4. What does print(total) print?
  5. What is the full output of this program?
Exercise 4
def is_even(n): return n % 2 == 0 print(is_even(4)) print(is_even(7)) result = is_even(10) print(result)
  1. What type of value does is_even return?
  2. What does is_even(4) return?
  3. What does is_even(7) return?
  4. What is the full output?
PracticeCode Tracing

Trace each program step by step. Write out every variable value as it changes. Predict the complete output before checking.

Trace 1
def add_tax(price, rate): tax = price * rate total = price + tax return total cost = add_tax(20.00, 0.10) print(cost)
StepVariableValue
Call add_tax(20.00, 0.10)price?
rate?
Inside functiontax?
total?
Return—?
After callcost?

What is printed?

Trace 2
def greet(name, message="Welcome"): return message + ", " + name + "!" a = greet("Yuki") b = greet("Sam", "Hello") print(a) print(b)

Trace both calls. What are a and b? What is the output?

Trace 3
def square(n): return n * n def sum_of_squares(x, y): return square(x) + square(y) print(sum_of_squares(3, 4))

Trace the call to sum_of_squares(3, 4). Note when square is called and what it returns each time. What is printed?

PracticePredict the Output

Read each program and write the exact output it will produce. Watch carefully for the difference between printing and returning.

Program 1
def halve(n): return n / 2 print(halve(10)) print(halve(7))
Program 2
def show_double(n): print(n * 2) result = show_double(5) print(result)
Program 3
def clamp(value, low, high): if value < low: return low elif value > high: return high else: return value print(clamp(3, 1, 10)) print(clamp(-5, 0, 100)) print(clamp(200, 0, 100))
Program 4
def describe(n, label="items"): return str(n) + " " + label print(describe(5)) print(describe(1, "apple")) print(describe(12, "eggs"))
Program 5
def add(a, b): return a + b x = add(2, 3) y = add(x, 10) z = add(y, add(1, 1)) print(z)
PracticePrint Versus Return Questions

These questions target the most common confusion in this chapter.

  1. A function computes a student's letter grade from a numeric score. Should it print the grade or return it? Explain your reasoning.
  2. A function's purpose is to display a formatted receipt to the user. Should it print or return? Explain.
  3. You write a function called calculate_discount. Another function, calculate_total, needs to use the discount in a further calculation. What does this tell you about how calculate_discount should be written?
  4. A student writes this code:
    def get_minimum(a, b): if a < b: print(a) else: print(b) lowest = get_minimum(8, 3) print("The minimum is:", lowest)

    What is the output? What is the bug? How would you fix it?

  5. A function has this line as its last statement: return. With no value after return, what does the function return?
PracticeDebugging Practice

Each program below contains one or more errors. Identify the error, explain what is wrong, and write a corrected version.

Bug 1
def rectangle_area(width, height): area = width * height print(area) room = rectangle_area(5, 8) flooring_cost = room * 12.50 print("Cost:", flooring_cost)
Bug 2
def power(base exponent): return base ** exponent print(power(2, 8))
Bug 3
def celsius_to_fahrenheit(c): f = (c * 9/5) + 32 return f temp = celsius_to_fahrenheit() print(temp)
Bug 4
def safe_divide(a, b): if b == 0: return 0 result = a / b return result print("Dividing...") print(safe_divide(10, 2)) print(safe_divide(10, 0))

(This code technically runs. What is wrong with it logically or stylistically?)

Bug 5
def greet_user(greeting="Hi", name): print(greeting + ", " + name) greet_user("Alice")
PracticeShort Programming Tasks

Write a complete Python function for each task. Test each function with at least two different sets of arguments.

  1. Write a function called calculate_perimeter that takes the length and width of a rectangle and returns the perimeter (2 × length + 2 × width).
  2. Write a function called is_passing that takes a score (0–100) and returns True if the score is 60 or above, and False otherwise.
  3. Write a function called full_name that takes a first name and a last name and returns them joined with a space between them.
  4. Write a function called clamp_temperature that takes a temperature and returns it unchanged if it is between -50 and 150 (inclusive), returns -50 if it is below -50, and returns 150 if it is above 150.
  5. Write a function called describe_bmi that takes a weight in kilograms and a height in meters, calculates the BMI (weight divided by height squared), and returns the BMI as a float rounded to one decimal place. (Use Python's round() function.)
  6. Write a function called repeat_string that takes a string and an integer and returns the string repeated that many times. For example, repeat_string("ha", 3) should return "hahaha".
  7. Write a function called shipping_cost that takes the weight of a package in kilograms and returns the shipping cost. The cost is 5.00 for the first kilogram and 2.50 for each additional kilogram. A default parameter should set the base rate to 5.00 and the per-kg rate to 2.50, but the caller can override either.
Mini-ProjectFunction-Based Calculator

Build a small calculator program using a collection of well-designed functions. Your calculator should support addition, subtraction, multiplication, and division.

Requirements

Each arithmetic operation should be its own function. Each function should take two numbers as parameters and return the result.

Division should handle the case where the second number is zero (return None or a message, and do not crash).

A main function should ask the user to enter two numbers and choose an operation, call the appropriate function, and display the result.

Starter Outline
def add(a, b): # return the sum def subtract(a, b): # return the difference def multiply(a, b): # return the product def divide(a, b): # return the quotient, handle division by zero def run_calculator(): # get input from user # call the right function # print the result run_calculator()
Extension Challenges

Add a power function that raises the first number to the power of the second. Add a square_root function using Python's ** operator (hint: the square root of n is n ** 0.5). Wrap the calculator in a loop so the user can keep calculating until they choose to quit. Add input validation so the program handles non-numeric input without crashing.

Sample Interaction
Enter the first number: 15 Enter the second number: 4 Choose an operation (add, subtract, multiply, divide): multiply Result: 60.0
ReviewMixed Review

These questions draw on skills from earlier chapters alongside the new material in Chapter 12.

  1. Write a function called count_even that takes two integers — a start and an end — and returns the count of even numbers in that range (inclusive of both endpoints). Use a for loop inside the function.
  2. Write a function called grade_letter that takes a numeric score and returns the letter grade: A (90–100), B (80–89), C (70–79), D (60–69), F (below 60). Use elif chains inside the function.
  3. A program collects three quiz scores from the user, stores them in three variables, and then calls a function average_of_three to calculate the average. Write both the function and the calling code.
  4. What is wrong with this code? Rewrite it correctly:
    def square_sum(a, b): return a * a + b * b print("The answer is: " + square_sum(3, 4))
  5. Explain in your own words why a function that only uses print() to show its result is harder to reuse than a function that uses return.
Chapter 12 Checklist
Use this to confirm your understanding before moving to Chapter 13
Concepts
  • I can explain why functions are more useful when they receive information rather than relying on fixed values.
  • I can define parameter and argument and explain how they are matched by position.
  • I can write and call functions with multiple parameters, supplying the correct number of arguments.
  • I can use the return statement to send a value back to the calling code.
  • I can explain the difference between printing a value and returning a value.
  • I can use a function's return value inside expressions, assignments, and other function calls.
  • I can explain what None is and why functions without return produce it.
  • I can write functions with default parameter values, placed in the correct order.
Applications
  • I can design a function interface — name, parameters, and return value — for a clearly stated task.
  • I can trace a function call by hand, tracking parameter values and the returned result.
  • I can identify and fix the "prints instead of returns" bug in someone else's code.
  • I have built a function-based calculator using separate functions for each operation.
Debugging Habits
  • I check whether a TypeError about argument counts comes from too few or too many arguments.
  • When a variable unexpectedly holds None, I check whether the function that produced it is missing a return.
  • I use is None rather than == None when testing for None.
Preview — Chapter 13
Scope, Local Variables, and Program State

Chapter 12 gave you tools for passing information into functions and getting results back. But there is an important question we have not fully answered yet: what happens to variables that are defined inside a function? Can the rest of the program see them? Can the function see variables defined outside it?

These questions are about scope — where a variable exists and how long it lives. Chapter 13 explores local variables, global variables, variable lifetime, and program state. You will learn why variables defined inside a function are separate from variables with the same name outside it, why functions should usually communicate through parameters and return values rather than sharing variables, and how to avoid the confusing bugs that arise when scope is misunderstood.

Understanding scope is essential before functions can be used to build larger, more organized programs.

MGU Library Connection
  • Programming with Python — Appendix G: Function Design Reference
  • Programming with Python — Appendix D: Common Python Error Messages
  • Companion resource: Function Design Guide
  • Companion resource: Print-Versus-Return Guide
  • Companion resource: Variable Tracing Worksheet
  • Next chapter: Chapter 13 — Scope, Local Variables, and Program State