0
if admin.isUserAdmin(): # This is on zero indent it's not inside a function or any other block
  if n == 0:
    global nzero
    nzero = df.to_string()
    print(nzero)
  elif n > 0:
    global ntrue
    ntrue = df.head(n).to_string()
    print(ntrue)
  while live_update:
    if n == 0:
      global nzero2
      nzero2 = df.to_string()
      print(nzero2)
    elif n > 0:
      global ntrue2
      ntrue2 = df.head(n).to_string()
      print(ntrue2)
print(nzero) #error nzero is not defined

I have much more complicated code but for the sake of convenience I've simplified things.

In the above program I want to make nzero, nzero2, ntrue and ntrue2 global that is it should be available outside the if block. but when I use it outside it gives me error saying nzero is not defined same is for nzero2, ntrue, ntrue2

2
  • Don't use global variables Commented Sep 29, 2020 at 19:33
  • 1
    global doesn't cause a variable to exist. It just makes sure that the name refers to a global variable if you do use it, rather than a local variable. Commented Sep 29, 2020 at 19:34

3 Answers 3

1

If all that code really is in module scope, then the global keyword does nothing anyway. You just need to initialize all names since not all branches necessarily assign to them.

nzero = None
ntrue = None
nzero2 = None
ntrue2 = None
n = None  # Or something? Who knows?

if admin.isUserAdmin():
    if n == 0:
        nzero = df.to_string()
        print(nzero)
    elif n > 0:
        ntrue = df.head(n).to_string()
        print(ntrue)
    while live_update:
        if n == 0:
            nzero2 = df.to_string()
            print(nzero2)
        elif n > 0:
            ntrue2 = df.head(n).to_string()
            print(ntrue2)
Sign up to request clarification or add additional context in comments.

Comments

1

Since your code is already at global scope, there is no need to use global. All variables are already global.

You get the error because some variables are defined inside the scope of an if statement. If that if clause doesn't execute then the variable is not available later. To fix the problem, just initialize the variables to a reasonable value before the if statement:

nzero = False
if admin.isUserAdmin():
...

Comments

0

The problem lies here:

if n == 0:
  global nzero
  nzero = df.to_string()
  print(nzero)
elif n > 0:
  global ntrue
  ntrue = df.head(n).to_string()
  print(ntrue)

If n is not 0, then nzero is never defined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.