Scope & Built-in Functions
Scope determines where a variable can be accessed. Understanding scope prevents subtle bugs. Python also provides powerful built-in functions that handle common tasks without importing anything.
Learning Objectives
- 11.3.2.2 Understand variable scope and use built-in functions
Conceptual Anchor
The Room and Building Analogy
Local scope is like items on your desk — only accessible in your room
(function). Global scope is like the building's lobby — accessible from any
room. You can see the lobby from your room but need explicit permission
(global) to change things there.
Rules & Theory
Variable Scope
# Global variable — accessible everywhere
message = "Hello"
def greet():
# Local variable — only inside this function
name = "Ali"
print(message) # ✓ Can READ global variable
print(name) # ✓ Can use local variable
greet()
print(message) # ✓ Global is accessible
# print(name) # ✗ NameError — local to greet()
# Scope Rules:
# 1. Local scope: variables defined INSIDE a function
# 2. Global scope: variables defined OUTSIDE all functions
# 3. A function CAN READ global variables
# 4. A function CANNOT MODIFY globals without the 'global' keywordThe
global Keyword
count = 0
def increment():
global count # Declare we're using the global variable
count += 1 # Now we can modify it
increment()
increment()
print(count) # 2
# WITHOUT global keyword:
x = 10
def broken():
x = 20 # Creates a NEW local variable named x!
print("Inside:", x)
broken() # Inside: 20
print("Outside:", x) # Outside: 10 — global x unchanged!Essential Built-in Functions
| Function | Description | Example | Result |
|---|---|---|---|
len(x) |
Length of sequence | len("hello") |
5 |
abs(x) |
Absolute value | abs(-5) |
5 |
round(x, n) |
Round to n decimal places | round(3.14159, 2) |
3.14 |
type(x) |
Type of object | type(42) |
<class 'int'> |
isinstance(x, t) |
Check type | isinstance(42, int) |
True |
int(x) |
Convert to integer | int("42") |
42 |
float(x) |
Convert to float | float("3.14") |
3.14 |
str(x) |
Convert to string | str(42) |
"42" |
bool(x) |
Convert to boolean | bool(0) |
False |
input(p) |
Read user input | input("Name: ") |
User's text |
print(*args) |
Output to screen | print(1, 2, 3) |
1 2 3 |
range(a, b, s) |
Number sequence | list(range(0,10,2)) |
[0,2,4,6,8] |
sum(iterable) |
Sum of elements | sum([1,2,3]) |
6 |
min(iterable) |
Smallest element | min(3,1,2) |
1 |
max(iterable) |
Largest element | max(3,1,2) |
3 |
sorted(iterable) |
New sorted list | sorted([3,1,2]) |
[1,2,3] |
Best Practice: Avoid global
Using global is generally discouraged because it makes code harder to debug. Prefer
passing values as parameters and using return values instead.
Worked Examples
1 Scope Tracing
x = 10 # Global
def func_a():
x = 20 # Local to func_a
print("A:", x)
def func_b():
print("B:", x) # Reads global x
func_a() # A: 20
func_b() # B: 10
print("G:", x) # G: 10 — global unchanged2 Using Built-in Functions Together
data = [15, -7, 23, -12, 8, 0, 42, -3]
print("Length:", len(data)) # 8
print("Sum:", sum(data)) # 66
print("Min:", min(data)) # -12
print("Max:", max(data)) # 42
print("Average:", round(sum(data)/len(data), 2)) # 8.25
# Filter positives using built-ins
positives = [x for x in data if x > 0]
abs_values = [abs(x) for x in data]
print("Positives:", positives) # [15, 23, 8, 42]
print("Absolute:", abs_values) # [15, 7, 23, 12, 8, 0, 42, 3]3 The Right Way — No global Needed
# BAD: using global
score = 0
def add_points_bad():
global score
score += 10
# GOOD: parameter + return
def add_points(current_score, points):
return current_score + points
my_score = 0
my_score = add_points(my_score, 10) # 10
my_score = add_points(my_score, 5) # 15
print(my_score)Pitfalls & Common Errors
UnboundLocalError
If you try to read and modify a global variable without global,
Python assumes it's local and crashes: x = x + 1 inside a function where
x is global causes UnboundLocalError.
Shadowing
Creating a local variable with the same name as a global "shadows" the global — you can no longer access the global version inside that function. Avoid using the same name.
Pro-Tips for Exams
Scope Rules Summary
- Function parameters are local variables
- Variables assigned inside a function are local
- A function can read global variables without
global - A function needs
global xto modify global x - Best practice: pass values as parameters, return results
Graded Tasks
What is the difference between local and global scope?
Why does modifying a global variable inside a function without global cause an
error?
Trace this code and predict the output:
x=5; def f(): x=10; print(x); f(); print(x)
Write a program using abs(), round(), min(),
max(), sum(), and len() to generate statistics for a
list of numbers.
Why is using global considered bad practice? Give a better alternative using
parameters and return values.
Write a quiz program where a function generates questions, another checks answers, and another tracks the score — without using global variables.
Self-Check Quiz
x = 5 inside a function?abs(-7) return?round(3.14159, 2) return?global?
isinstance("hello", str) return?