Scope of Variable and Return statements
M3-R5.1 · Chapter 6: Functions · 2 min read
Scope of Variables
Scope refers to the region of a program where a variable is accessible. Python has two main scopes:
|
Scope |
Where defined |
Where accessible |
Keyword to modify |
|
Local Variable |
Inside a function |
Only within that function; not accessible outside |
— |
|
Global Variable |
Outside all functions |
Anywhere in the program (file) |
global |
x = 10 # Global variable
def show():
y = 20 # Local variable
print('x =', x) # Can access global x
print('y =', y)
show() # Output: x = 10 y = 20
# print(y) # Error: y is not defined outside the function
# Modifying a global variable inside a function by using global keyword
count = 0
def increment():
global count # Declare we are using the global count
count += 1
increment()
increment()
print(count) # Output: 2
The return Statement
The return statement exits a function and optionally sends a value back to the caller.
|
Scenario |
Behaviour |
Example |
|
return value |
Exits function and returns the specified value to caller |
return s |
|
return (no value) |
Exits function; caller receives None |
return |
|
No return at all |
Function runs to end; caller receives None |
(no return statement) |
|
Multiple values |
Returns a tuple; can be unpacked by caller |
return x, y, z |
# Return a single value
def square(n):
return n * n
print(square(5)) # Output: 25
# Return multiple values
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 9, 5])
print('Min:', lo, 'Max:', hi) # Output: Min: 1 Max: 9
# No return (returns None implicitly)
def say_hi():
print('Hi!')
result = say_hi() # Output: Hi!
print(result) # Output: None