1

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?

Hari
  • 718
  • 3
  • 9
  • 30
Alex Deft
  • 2,531
  • 1
  • 19
  • 34
  • Can you show a screenshot of this happening in the debug console? – user2357112 Jun 18 '19 at 01:43
  • @user2357112 Exactly what you see above. – Alex Deft Jun 18 '19 at 01:44
  • What I see above doesn't include the error message, and is missing a lot of other useful context as well. – user2357112 Jun 18 '19 at 01:46
  • Sorry. Here is the error: Traceback (most recent call last): File "C:\Users\s4551072\.conda\envs\tfbetacpu\lib\site-packages\IPython\core\interactiveshell.py", line 3296, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in b NameError: name 'a' is not defined – Alex Deft Jun 18 '19 at 01:48
  • Other than that, it is exactly as above. – Alex Deft Jun 18 '19 at 01:50

1 Answers1

0

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.

Community
  • 1
  • 1
howie
  • 2,587
  • 3
  • 27
  • 43
  • This is weird cause I usually don't have to declare anything first. Say if I used Jupyter, or did it in the main program. – Alex Deft Jun 18 '19 at 01:35
  • You can also see this https://stackoverflow.com/questions/10588317/python-function-global-variables – howie Jun 18 '19 at 01:40
  • 1
    There is ordinarily no need to declare the variable first. The code in the question [works fine](https://ideone.com/Kq23B5) when run as a script. – user2357112 Jun 18 '19 at 01:43
  • Yes I know. It only happens in debugging console. – Alex Deft Jun 18 '19 at 01:55