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
returngives backNone. - 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.
print() call.def area(width, height):
return width * height
room = area(12, 15)
print("Living room:", room, "square feet")
print(area(10, 10))area has two parameters, width and height, measured in feet.return width * height calculates the product and sends it back to whoever called the function.area(12, 15) is replaced by 180, and that number is stored in the variable room.Living room: 180 square feet.print(). The function returns 100, so the output is 100.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.
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)show_total will display a message. It has no return statement.get_total does the same calculation but will send the answer back instead of printing it.return hands the rounded total to the caller. Nothing appears on the screen yet.Total: 54.0 as it runs. Because it returns nothing, a is set to None.54.0 is stored in b. No output is shown yet.None. This is what every function returns when it has no return statement.54.0. This value can be reused in later calculations.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.
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))min_max takes one parameter, a list of temperatures in degrees Fahrenheit.min(temps), max(temps) is a pair of values. Python packs them into the tuple (49, 77) and returns it.low becomes 49 and high becomes 77.Low: 49 High: 77.(49, 77).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.
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))grade_letter receives a numeric score."A" and stops. None of the lines below run for this score."B" and the function ends."C".return and gives "Below C". Every path now returns a value.s.95 A, 84 B, 72 C, and 55 Below C, each on its own line.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.
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")make_receipt takes no parameters.tip is created inside the function, so it is local. It exists only while the function runs.Tip inside: 4.5.tip is removed from memory.try block lets the program attempt something that might fail.tip exists, so Python raises a NameError.except NameError: catches that specific error instead of stopping the program.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.
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)tax_rate is defined outside every function, so it is global. 0.07 means a 7% sales tax.price_with_tax receives a price as its parameter.tax_rate, so Python finds it in the global scope. It returns the price plus 7% tax, rounded to two decimals.change_rate will try to use the same name as the global variable.tax_rate. The global one is untouched.0.1.107.0, calculated with the global rate of 7%.0.1, which is the local variable.0.07. The global variable was never changed.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.
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)visitors is a global variable that starts at zero.check_in receives the name of the visitor.global visitors tells Python that the name refers to the global variable. Without this line, the next line would raise an UnboundLocalError.Emily checked in at the Denver library. Visitors: 1.Jackson checked in at the Denver library. Visitors: 2.2.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.
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())make_counter receives the starting number.count is local to make_counter. It will be shared with the inner function.step is defined inside make_counter, so it can see count.nonlocal count says that count belongs to the enclosing function. This lets the inner function change it.step returns the updated number.return step returns the function itself, without calling it. The variable count stays alive because step still needs it.houston now holds the inner function.101.102.count variable that starts at 0, separate from Houston’s.1. The two counters do not affect each other.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.
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)input() reads the first line of the Program Input box as a string, such as "48.50 20".split() breaks the text at the space, and the two pieces are unpacked into bill and percent. Both are still strings.amount and tip_percent are required. people=2 is optional with a default of two.float() converts the text to numbers before the call. The returned tuple is unpacked into total and each.Total with tip: 58.2.Each person pays: 29.1.Tip: If a function needs to give you information, usereturn. If you find yourself reaching forglobalto 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, sototal = show_total(50)stores nothing useful. - Forgetting return on some paths: if an
ifbranch has noreturnand nothing follows it, the caller receivesNone. - Code after return: lines written after a
returnin the same block never run. - Using a local variable outside: a name created inside a function raises a
NameErroroutside it. Return the value instead. - Assigning to a global without declaring it:
count = count + 1inside a function raises anUnboundLocalErrorunless you writeglobal 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 stepreturns the function, whilereturn step()returns its result. - Unpacking the wrong count:
a, b = f()fails with aValueErroriff()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.
returnsends a value back to the caller and ends the function immediately.- A function with no
returngives backNone. - 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
globalandnonlocalonly 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.