Home > Software engineering >  when I declare the variable global and use it in another function it shows this error NameError: nam
when I declare the variable global and use it in another function it shows this error NameError: nam

Time:06-20

In this code, I am writing a function to get the images only from the folder which contains a corresponding txt file, so when i use the declared variable in another function it shows error

is it because the global variable is inside a loop?

import os

def open_image():
  global img_file
  EXT = ['.jpeg','.png','.jpg']
  path = os.getcwd()
  mydir = os.listdir(path)
  for i in mydir:
    k = os.path.splitext(i)
    if k[1] in EXT:
      img_file = k[0] k[1]

def image():
  print(img_file)

image()

CodePudding user response:

Declare img_file in a global scope by moving it out of your function. Call open_image to populate the list and thecall the image() function to print it. Or call the open_image in the image function, whatever fits your use-case

import os

img_file=[]

def open_image():
  EXT = ['.jpeg','.png','.jpg']
  path = os.getcwd()
  mydir = os.listdir(path)
  for i in mydir:
    k = os.path.splitext(i)
    if k[1] in EXT:
      img_file.append(k[0] k[1])

def image():
  print(img_file)

open_image()
image()

CodePudding user response:

You need to call open_image() funciton where global variable is declared .

import os

def open_image():
  global img_file
  EXT = ['.jpeg','.png','.jpg']
  path = os.getcwd()
  mydir = os.listdir(path)
  for i in mydir:
    k = os.path.splitext(i)
    if k[1] in EXT:
      img_file = k[0] k[1]
open_image()
def image():
  print(img_file)

image()

CodePudding user response:

Python: to use a local variable inside of another function we use func

def func():
  func.name = "Ali Axghar"

func()
print(func.name)

Output: Ali Axghar

  • Related