Juned Khan
Juned Khan

Reputation: 122

Global variables name is not defined error in python

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

Upvotes: 0

Views: 952

Answers (3)

AKX
AKX

Reputation: 169378

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)

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83577

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():
...

Upvotes: 1

VirxEC
VirxEC

Reputation: 1054

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.

Upvotes: 0

Related Questions