Python函数无法访问全局变量报错问题排查求助
largest Variable? Hey there! Let's sort out this error you're hitting. First, let's recap your code and the error you're seeing:
Your Code
numbers = [23, 5, 12, 94, 5 , 43, 23, 59, 10, 59, 31] largest = 0 def find_largest(x): for num in x: if num > largest: largest = num return largest max_number = find_largest(numbers) print(max_number)
The Error You're Getting
Traceback (most recent call last):
File "largestElement.py", line 9, in
max_number = find_largest(numbers)
File "largestElement.py", line 5, in find_largest
if num > largest:
UnboundLocalError: local variable 'largest' referenced before assignment
What's Going On Here?
The problem boils down to Python's scoping rules: when you assign a value to a variable inside a function, Python automatically treats that variable as a local variable to the function—even if there's a global variable with the exact same name.
In your code, writing largest = num inside the loop tells Python to treat largest as local to find_largest(). Then, when it hits the line if num > largest: before the first assignment to the local largest, it throws an error because that local variable hasn't been initialized yet.
Fixes You Can Use
1. Use the global Keyword (Quick Fix)
You can explicitly tell Python that largest is a global variable by declaring it inside the function. This way, Python won't treat it as a local variable:
numbers = [23, 5, 12, 94, 5 , 43, 23, 59, 10, 59, 31] largest = 0 def find_largest(x): global largest # Declare we're using the global variable for num in x: if num > largest: largest = num return largest max_number = find_largest(numbers) print(max_number)
This works, but relying on global variables can make code harder to debug and maintain as it grows, so it's not the best long-term practice.
2. Avoid Global Variables (Cleaner, Recommended Fix)
A better approach is to keep the function self-contained by initializing largest inside it or passing it as a parameter. This eliminates dependency on external state:
Option A: Initialize largest inside the function
numbers = [23, 5, 12, 94, 5 , 43, 23, 59, 10, 59, 31] def find_largest(x): if not x: # Handle empty list to avoid edge-case errors return None largest = x[0] # Start with the first element as initial largest for num in x[1:]: if num > largest: largest = num return largest max_number = find_largest(numbers) print(max_number) # Output: 94
This is better because:
- The function can be reused anywhere without worrying about external variables.
- We added a check for empty lists to prevent crashes.
- Starting with the first element instead of 0 fixes a bug where your original code would return 0 for a list of negative numbers (like
[-5, -2]).
Option B: Use Python's Built-in max() Function
If you don't need to implement the logic yourself for learning purposes, Python has a built-in function that does exactly this:
numbers = [23, 5, 12, 94, 5 , 43, 23, 59, 10, 59, 31] max_number = max(numbers) print(max_number) # Output: 94
This is the simplest and most Pythonic solution for finding the largest element in a list.
内容的提问来源于stack exchange,提问作者jamesjsewell

