Academic Block

Python return, Scope & LifetimeGet Certified

What Are return, Scope, and Lifetime?

So far your functions have received information through parameters. This lesson is about the other direction: how a function sends a result back, and where the variables inside it can be seen. These ideas decide whether your code is clean and predictable or full of surprising bugs.

The return statement hands a value back to the code that called the function. Scope describes the parts of a program where a variable name can be used. Lifetime describes how long a variable stays alive in memory. A local variable is born when the function starts and disappears when it ends.

  • return: ends the function and sends a value back to the caller.
  • No return: a function without return gives back None.
  • Local scope: variables created inside a function exist only inside that function.
  • Global scope: variables created outside every function can be read anywhere in the file.
  • LEGB rule: Python looks for a name in Local, Enclosing, Global, and Built-in scopes, in that order.
  • Lifetime: local variables are created when a call starts and removed when it finishes.

Returning a Value

A function that returns a value can be used like any other value in your program. You can store the result in a variable, print it, pass it into another function, or use it in a calculation. This is what makes functions the building blocks of larger programs.

The moment Python reaches a return statement, the function stops and the value is sent back. Any lines after the return in that path are never run. The call itself, such as area(12, 15), is replaced by the returned value.

Try It: Measure Rooms in Square Feet

Click Test My Code to run the program. Then change the width and height to match a room in your own home.

What this code does: It defines a function that returns the area of a rectangle. The result is stored in a variable and printed, and then the function is used directly inside a print() call.
def area(width, height):
    return width * height
room = area(12, 15)
print("Living room:", room, "square feet")
print(area(10, 10))

return vs print()

Beginners often mix up return and print(). They look similar when you run a small program, but they do very different jobs. print() only shows text on the screen for a human to read. return gives a value back to the program so it can be used again.

A function that prints but does not return gives back None, which means “no value”. If you try to use that result in a calculation, you will get an error or a wrong answer. As a rule, let functions return their results and print only at the outer level of your program.

Try It: Sales Tax in Texas

Click Test My Code. Then change the price and compare what each function gives back.

What this code does: It compares two functions that add 8% sales tax. One only prints the total, and the other returns it. The program then prints what each function gave back.
def show_total(price):
    print("Total:", round(price * 1.08, 2))
def get_total(price):
    return round(price * 1.08, 2)
a = show_total(50)
b = get_total(50)
print(a)
print(b)

Returning Multiple Values

Sometimes a function needs to report more than one result, such as both the lowest and the highest temperature of a week. Python makes this easy: separate the values with commas after return. Python quietly packs them into a single tuple.

The caller can then unpack the tuple into separate variables in one step, as in low, high = min_max(daily). The number of variables on the left must match the number of values returned. Returning a tuple is cleaner than using global variables to pass results around.

Try It: Weekly Temperatures in Denver

Click Test My Code. Then replace the temperatures with your own city’s week of weather.

What this code does: It defines a function that returns both the lowest and the highest temperature of a list. The result is unpacked into two variables and also printed as a tuple.
def min_max(temps):
    return min(temps), max(temps)
daily = [58, 71, 64, 49, 77]
low, high = min_max(daily)
print("Low:", low, "High:", high)
print(min_max(daily))

Early return and Multiple Exit Points

A function can contain more than one return statement. This is very useful with if statements, because you can return an answer as soon as you know it. The rest of the function is skipped, which often removes the need for deeply nested else blocks.

Make sure every path through your function ends with a return, or the caller will quietly receive None on the paths that do not. A final return at the bottom, like a default answer, is a good safety net. Readable early returns are a hallmark of clean Python code.

Try It: Convert Scores to Letter Grades

Click Test My Code. Then add your own scores to the list.

What this code does: It returns a letter grade for a numeric score. The function checks the highest grade first and returns immediately when a test passes. A loop then grades four scores.
def grade_letter(score):
    if score >= 90:
        return "A"
    if score >= 80:
        return "B"
    if score >= 70:
        return "C"
    return "Below C"
for s in [95, 84, 72, 55]:
    print(s, grade_letter(s))

Local Scope

A variable created inside a function has local scope. It can be used only within that function, and it is removed when the function finishes. Parameters are local variables too. This protects your program, because two functions can use the same variable name without interfering with each other.

If you try to use a local variable outside its function, Python raises a NameError because the name does not exist there. Beginners meet this error very often. The fix is almost always to return the value from the function instead of trying to reach inside it.

Try It: A Variable That Disappears

Click Test My Code. Then try printing tip without the try block to see the error message.

What this code does: It creates a variable inside a function, prints it there, and then tries to print it outside the function. The error is caught so the program can show a friendly message.
def make_receipt():
    tip = 4.50
    print("Tip inside:", tip)
make_receipt()
try:
    print(tip)
except NameError:
    print("tip does not exist outside the function")

Global Variables and Shadowing

A variable created outside every function has global scope. Any function can read a global variable, which is handy for fixed settings such as a tax rate. Python follows the LEGB rule when it looks for a name: Local, Enclosing, Global, then Built-in.

If a function assigns to a name, Python treats that name as a brand new local variable, even if a global variable has the same name. This is called shadowing. The global variable is not changed, which surprises many beginners. Using different names for local and global variables avoids the confusion.

Try It: Reading a Global and Shadowing It

Click Test My Code. Then change the global tax rate and watch which outputs change.

What this code does: One function reads the global tax rate to price an item. Another function creates a local variable with the same name, which hides the global one without changing it.
tax_rate = 0.07
def price_with_tax(price):
    return round(price * (1 + tax_rate), 2)
def change_rate():
    tax_rate = 0.10
    return tax_rate
print(price_with_tax(100))
print(change_rate())
print(tax_rate)

The global Keyword

Sometimes a function really does need to change a global variable, such as a running count of visitors. The global keyword tells Python that a name inside the function refers to the global variable, not a new local one. Without it, assigning to the name would create a local variable and fail.

Use global sparingly. Functions that change global variables are harder to test, because their behavior depends on hidden state outside them. In most programs it is better to pass values in as parameters and return the new value. Think of global as a tool for small scripts, not large projects.

Try It: Count Library Visitors in Denver

Click Test My Code. Then check in a third visitor with your own name.

What this code does: It keeps a running count of visitors in a global variable. Each call to the function adds one to the count and prints a message.
visitors = 0
def check_in(name):
    global visitors
    visitors = visitors + 1
    print(name, "checked in at the Denver library. Visitors:", visitors)
check_in("Emily")
check_in("Jackson")
print(visitors)

Nested Functions, nonlocal, and Lifetime

A function can be defined inside another function. The inner function can read the variables of the outer function, which is the Enclosing scope in the LEGB rule. To change an enclosing variable, the inner function must declare it with the nonlocal keyword.

This leads to a surprising fact about lifetime. When the outer function returns the inner function, the enclosing variables stay alive because the inner function still needs them. This is called a closure. Each call to the outer function creates its own separate set of variables, so counters do not interfere with each other.

Try It: Two Independent Counters

Click Test My Code. Then call houston() one more time and predict the output first.

What this code does: It builds a counter function that remembers its count between calls. Two counters, one for Houston and one for Dallas, start at different numbers and keep their own separate counts.
def make_counter(start):
    count = start
    def step():
        nonlocal count
        count = count + 1
        return count
    return step
houston = make_counter(100)
print(houston())
print(houston())
dallas = make_counter(0)
print(dallas())

Using Return Values with input()

Functions that return values fit naturally with user input. You read text with input(), convert it to numbers, and pass it into a function. The function does the work and returns the answer, and the main program decides how to display it.

This separation keeps your logic reusable. The same function could be called from a button, a file, or another function, because it never prints or reads anything itself. Remember that input() always gives text, so convert values with int() or float() before calculating.

Try It: Split a Restaurant Bill in Seattle

The Program Input box is already filled with one line: 48.50 20. Click Run Code straight away, then try another bill and tip percent separated by a space.

What this code does: It reads a bill amount and a tip percentage, then calls a function that returns two values: the total with tip and the amount each of two people pays.
text = input("Bill and tip percent: ")
bill, percent = text.split()
def split_bill(amount, tip_percent, people=2):
    tip = amount * tip_percent / 100
    total = amount + tip
    return round(total, 2), round(total / people, 2)
total, each = split_bill(float(bill), float(percent))
print("Total with tip:", total)
print("Each person pays:", each)
Tip: If a function needs to give you information, use return. If you find yourself reaching for global to move data out of a function, that is usually a sign to return the value instead.

Common Mistakes with return and Scope

Almost every beginner meets these problems, and most of them produce confusing error messages the first time. Knowing the patterns will save you a lot of debugging time. When something looks wrong, ask yourself two questions: does the function return what I expect, and can this name be seen from here?

  • Printing instead of returning: a function that only prints gives back None, so total = show_total(50) stores nothing useful.
  • Forgetting return on some paths: if an if branch has no return and nothing follows it, the caller receives None.
  • Code after return: lines written after a return in the same block never run.
  • Using a local variable outside: a name created inside a function raises a NameError outside it. Return the value instead.
  • Assigning to a global without declaring it: count = count + 1 inside a function raises an UnboundLocalError unless you write global count.
  • Accidental shadowing: a local variable with the same name as a global hides it and can hide bugs. Use distinct names.
  • Calling vs returning a function: return step returns the function, while return step() returns its result.
  • Unpacking the wrong count: a, b = f() fails with a ValueError if f() returns three values.

Good Habits for return and Scope

Clean functions behave like small machines: values go in through parameters, one clear result comes out through return, and nothing else is changed along the way. Following a few simple habits keeps your functions easy to read, test, and reuse in other programs.

  • Let functions return results and print only in the main part of your program.
  • Give each function one clear job and one clear kind of return value.
  • Make sure every path through a function ends with a return, even if the value is a default.
  • Prefer parameters and return values over global variables.
  • Use ALL_CAPS names for global constants, such as TAX_RATE, so they are easy to recognize.
  • Keep variables in the smallest scope that works. Declare them inside the function that needs them.

Key Takeaways

Return values and scope are the rules that keep functions independent of one another. Once you understand them, you can predict what a function will give back and where each variable can be used. Review the points below before moving on to lambda functions.

  • return sends a value back to the caller and ends the function immediately.
  • A function with no return gives back None.
  • Returning several values with commas produces a tuple that can be unpacked.
  • Local variables exist only while their function runs.
  • Python looks up names in the order Local, Enclosing, Global, Built-in (LEGB).
  • Use global and nonlocal only when a function must change a variable from an outer scope.
  • A closure keeps its enclosing variables alive after the outer function has returned.

Frequently Asked Questions

These are the questions students ask most often about return values, scope, and variable lifetime. Each answer is short and uses the same rules you practiced in the examples. Open a question to read its answer, and run the matching example again if something is still unclear.

What does return do in Python?

The return statement ends a function and sends a value back to the code that called it. The call is replaced by that value, so you can store it in a variable, print it, or use it in a calculation. Any code after the return in the same path is not run.

What is the difference between return and print in Python?

print() only displays text on the screen for a person to read. return gives a value back to the program so it can be used again. A function that only prints returns None, which cannot be used in later calculations.

What does a function return if there is no return statement?

A function without a return statement returns None, which is Python’s value for “nothing”. The same happens if the function finishes without reaching a return, for example when an if branch has no return.

Can a Python function return more than one value?

Yes. Write the values separated by commas after return, such as return low, high. Python packs them into a tuple, and the caller can unpack them with low, high = min_max(data). The number of variables must match the number of values.

What is variable scope in Python?

Scope is the part of a program where a variable name can be used. Python searches Local, Enclosing, Global, and Built-in scopes in that order, known as the LEGB rule. A variable created inside a function is local and cannot be used outside it.

When should I use the global keyword?

Use global when a function must assign a new value to a variable defined outside it. Without it, assigning to the name creates a new local variable. In most cases it is cleaner to pass values in as parameters and return the new value instead.

What is the difference between global and nonlocal?

global refers to a variable in the module’s global scope. nonlocal refers to a variable in the nearest enclosing function, which is useful inside a nested function. Both let you assign to a name from an outer scope instead of creating a new local variable.

How long does a local variable live in Python?

A local variable is created when the function call starts and is removed when the call ends. Each call gets its own fresh variables. The exception is a closure, where an inner function keeps the enclosing variables alive after the outer function has returned.

Ready for the next step?Learn how to write short, unnamed functions in a single line.
Next: Lambda Functions →