首页 > 解决方案 > Function declaring global variable doesn't work in debug mode

问题描述

I'm debugging a program. In the debug console, I decided to write the following function:

def func():
    global a
    a=5

func()

a

a is undefined!

Why does this happens in the debug console?

标签: pythonpycharm

解决方案


If you want to use a outside function, you should declare it first.

a = 0

def func():
    global a
    a=5

func()
print(a)

In this case will be 6 and 3

test=6
def func():
    global test
    print(test)
    test=3
f()
print(test)

FYI: What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.


推荐阅读