You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数混用全局与局部变量的报错问题及实现需求

Fixing the UnboundLocalError in Your Python Function

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:36:14