Python函数混用全局与局部变量的报错问题及实现需求
Hey there! Let's break down why you're hitting that UnboundLocalError and fix it to match your exact requirement.
Why the Error Happens
Python has strict rules about variable scope. In your original code, since you have the line admin = "other" inside the else block, Python treats admin as a local variable for the entire function. That means when the if default == "default" branch runs and tries to print admin, Python looks for a local admin (not the global one) — but it hasn't been defined yet, hence the error.
Solution 1: Use a Different Local Variable Name
The simplest fix is to avoid reusing the admin name for your local variable. This way, Python will automatically fall back to the global admin when you need it:
admin = "Vaibhav" def print_admin(default): if default == "default": print(admin) # Uses the global variable since no local assignment exists else: local_admin = "other" print(local_admin) print_admin("") print_admin("default")
Solution 2: Explicitly Manage the Value with a Local Variable
If you prefer to keep the logic focused on a single variable, you can start by grabbing the global value, then override it only when needed:
admin = "Vaibhav" def print_admin(default): # Start with the global admin value current_admin = admin # Override if the parameter isn't "default" if default != "default": current_admin = "other" print(current_admin) print_admin("") print_admin("default")
Both solutions will give you the behavior you want:
- When you pass
"default", it prints the global"Vaibhav" - When you pass any other value (including an empty string), it prints
"other"
内容的提问来源于stack exchange,提问作者Va_M

