Help me with global | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help me with global

When creating a discord bot, when I wanted to import data from a file, I had a problem with the "for" loop. More precisely, with the variable "d". Code: class Data(object): def __init__(self): with open("data.dt", "r") as file: l = file.readlines() self.wl = l[0].split() # whitelist s = l[1].split() for i in s: k = i.split(":") d[k[0]] = k[1] self.score = d # score del s, k, d data = Data() Error: UnboundLocalError: local variable 'd' referenced before assignment I tried to put "global d" both before loop and inside it, before the "Data" class and in many other places. I get an error like "NameError: name "d" is not defined".

31st May 2021, 9:54 AM
Operand
Operand - avatar
4 Answers
0
I have already solved the problem without "global". But I don't know how :D class Data(object): def __init__(self): with open("data.dt", "r") as file: l = file.readlines() self.wl = l[0].split() # whitelist d = {} for x in list(l[1].split()): s = x.split(":") d[s[0]] = s[1] self.score = d # score del d data = Data()
31st May 2021, 10:57 AM
Operand
Operand - avatar
+ 1
in your solution you have defined a variable 'd' as an empty dict before the loop, so in the loop you can access it without problem ;P however, you doesn't need to explicitly delete it, as local variable live only during function/method run (since you doesn't capture the scope by returning some function defined in that scope) ^^
31st May 2021, 6:12 PM
visph
visph - avatar
0
all that means is that you tried to acces a variable (d) that wasn't created yet. what where you trying to do with that line d[k[0]] = k[1]
31st May 2021, 10:18 AM
Slick
Slick - avatar
0
visph Thank you :)
1st Jun 2021, 4:15 AM
Operand
Operand - avatar