So far, you've seen how to send values into a function. In this chapter, we'll look at the other direction: how a function sends a result back using return.
We'll also answer a question that confuses many beginners: "Why can't I use a variable from inside my function outside it?" The answer is scope.
The return Statement
The return statement ends the function and sends a value back to the place where the function was called.
def add(a, b):
return a + b
total = add(10, 5)
print(total)
print(add(2, 3) * 10)Output:
15
50You can think of the function call as being replaced by the returned value:
print(add(2, 3) * 10)
|
v
print( 5 * 10)
|
v
print(50)print vs return
This is the most common confusion with functions. They look similar when you test them, but they are very different:
def square_print(n):
print(n * n)
def square_return(n):
return n * n
a = square_print(4)
b = square_return(4)
print("a =", a)
print("b =", b)Output:
16
a = None
b = 16square_print(4)displays 16 on the screen, but gives nothing back. SoabecomesNone.square_return(4)displays nothing, but gives back 16, which we can store, print, or use in calculations.
|
|
|---|---|
Shows a value to the user | Gives a value back to the code |
The value cannot be reused | The value can be stored and reused |
Function continues after it | Function stops immediately |
As a rule of thumb, functions that calculate something should return the result. Let the caller decide whether to print it.
Functions Without return Return None
If a function has no return statement, or just writes return with no value, it returns None automatically:
def greet():
print("Hi!")
result = greet()
print(result)Output:
Hi!
Nonereturn Stops the Function Immediately
As soon as Python reaches a return, it leaves the function. Any code after it is skipped:
def check_age(age):
if age < 18:
return "Minor"
return "Adult"
print("This line never runs")
print(check_age(15))
print(check_age(25))Output:
Minor
AdultThis "early return" is very handy inside loops. For example, checking whether a number is prime:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False # found a divisor, stop right away
return True
for num in [1, 2, 9, 13, 25, 29]:
print(num, is_prime(num))Output:
1 False
2 True
9 False
13 True
25 False
29 TrueWe only need to check divisors up to the square root of n, so this runs in O(√n) time.
Returning Multiple Values
A Python function can return more than one value by separating them with commas:
def min_max(a, b, c):
smallest = min(a, b, c)
largest = max(a, b, c)
return smallest, largest
low, high = min_max(7, 2, 9)
print(low, high)
result = min_max(7, 2, 9)
print(result)
print(type(result))Output:
2 9
(2, 9)
<class 'tuple'>Behind the scenes, Python packs the values into a single tuple. Writing low, high = ... unpacks it into separate variables. The number of variables on the left must match the number of values returned.
What is Scope?
Scope is the region of a program where a variable can be seen and used.
Local Variables
A variable created inside a function is local to that function. It exists only while the function runs and cannot be used outside it:
def calculate():
result = 42
print("Inside:", result)
calculate()
print("Outside:", result)Output:
Inside: 42
NameError: name 'result' is not definedEach call gets a fresh set of local variables. When the function finishes, they are thrown away. If you need the value outside, return it.
Global Variables
A variable created at the top level of your file (outside every function) is global. Functions can read it:
college = "IIT Bombay"
def show_college():
print("College:", college)
show_college()Output:
College: IIT BombaySame Name, Different Variables
If you assign to a variable inside a function, Python creates a new local variable, even if a global one has the same name:
x = 10
def change():
x = 99 # a new local x
print("Inside:", x)
change()
print("Outside:", x)Output:
Inside: 99
Outside: 10The global x is untouched. The two x variables simply share a name.
The UnboundLocalError Trap
What if you try to update a global variable inside a function?
count = 0
def increment():
count += 1
increment()Output:
UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueBecause count += 1 assigns to count, Python decides that count is a local variable for the whole function. Then it tries to read that local count before it has a value, and fails.
The global Keyword
To modify a global variable inside a function, declare it with global:
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)Output:
2This works, but use global sparingly. Functions that change global variables are harder to understand and test. A cleaner approach is to pass values in and return the result:
def increment(value):
return value + 1
count = 0
count = increment(count)
count = increment(count)
print(count)Output:
2Nested Functions and nonlocal
You can define a function inside another function. The inner function can read variables of the outer function. These are called enclosing variables.
To modify an enclosing variable, use nonlocal:
def outer():
message = "original"
def inner():
nonlocal message
message = "changed by inner"
inner()
print(message)
outer()Output:
changed by innerWithout nonlocal, inner() would create its own local message and the outer one would still be "original".
The LEGB Rule
When Python sees a variable name, it searches for it in four scopes, in this order:
L - Local : inside the current function
E - Enclosing : inside any outer (enclosing) functions
G - Global : at the top level of the file
B - Built-in : names Python provides, like print, len, maxPython uses the first match it finds. Here's an example showing all of them:
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
print(x)
outer()
print(x)
print(len("abc")) # len is found in the built-in scopeOutput:
local
enclosing
global
3This also explains a sneaky bug. If you create a variable called list, max or sum, it hides the built-in one, because Global is searched before Built-in:
sum = 10
print(sum([1, 2, 3]))Output:
TypeError: 'int' object is not callableAvoid using built-in names as variable names.
Summary
returnsends a value back to the caller and ends the function immediately.print()only displays a value. A function withoutreturngives backNone.Returning
a, bactually returns a tuple, which you can unpack.Variables created inside a function are local; variables at the top level are global.
Assigning inside a function creates a local variable. Use
globalornonlocalonly when you really need to modify an outer variable.Python looks up names using the LEGB rule: Local, Enclosing, Global, Built-in.
Pass data in through parameters, send results out with return, and keep variables local whenever you can.