0

I am writing an app, and I need to set the background of the elements correspondingly, so I wrote this little code that makes a variable for every language background. It works perfectly when run in main (without any modifications), but like a function, it doesn't! Here is the code I'm talking about:

available_languages = ["english", "german", "spanish", "ukrainian", "russian", "italian",
                               "portuguese", "french", "arabic", "mandarin", "japanese", "hindi"]

current = "english"

for current_language in available_languages:
    if current == current_language:
        exec(current_language + "bg = [.7, .7, .7, 1]")
        print(englishbg)

    else:
        exec(current_language + "bg = [0, 0, 0, 0]")

print(englishbg)

Now when I run it as a function like this:

def getlanguagelists():
    available_languages = ["english", "german", "spanish", "ukrainian", "russian", "italian",
                                   "portuguese", "french", "arabic", "mandarin", "japanese", "hindi"]

    current = "english"

    for current_language in available_languages:
        if current == current_language:
            exec(current_language + "bg = [.7, .7, .7, 1]")
            print(englishbg)

        else:
            exec(current_language + "bg = [0, 0, 0, 0]")

    print(englishbg)

getlanguagelists()

I get this exception:

Traceback (most recent call last):
  File "C:\Users\siuba\Desktop\t.py", line 17, in <module>
    getlanguagelists()
  File "C:\Users\siuba\Desktop\t.py", line 10, in getlanguagelists
    print(englishbg)
NameError: name 'englishbg' is not defined

Why could this happen?

Yaros
  • 175
  • 8
  • You will need to tell us what exactly doesn't work when it's in a function (is an error raised, does it do the wrong thing, does it do nothing, etc?), and ideally show us what the function looks like. – Kemp Mar 29 '21 at 13:56
  • I added the necessary changes! Check again! @Kemp – Yaros Mar 29 '21 at 13:58
  • I assume the issue is that exec will place the variable into the global scope, which your function won't look in by default. I don't have a solution for you, but I will say the exec is generally a bad idea. Could you put the value into a dictionary with `current_language + "bg"` as the key instead? – Kemp Mar 29 '21 at 14:04
  • Okay, I will try to use a list or dictionary instead! Thanks! – Yaros Mar 29 '21 at 14:06

0 Answers0