Ask coding questions

← Back to all posts
Globals not working
BrandonBailey3 (5)

Alright, #1 I know that I've already leeched my share from the community. #2 I declare swamptf as global but it doesn't work.

Answered by LukeWright (114) [earned 5 cycles]
View Answer
Comments
hotnewtop
LukeWright (114)

Instead of using global variables, I prefer to use classes. you can create on by simply doing

class vars:
 swamptf = None #(Or Whatever you want it to be)
 curr = None
 currh = 20
 #add more variables as neccessary

then you can call them by simply doing:

print(vars.swamptf)
print(vars.currh)
print(vars.curr)

click the checkmark next to my comment if this helped!

InvisibleOne (2672)

You don't need to make swamptf a global variable, the error is because you have not assigned it a value yet. Variables in python must be assigned a value at creation, if you don't want to give it a real value then just set it to swamptf = '' but you can't just do global swamptf
I suggest you change that to.

swamptf = ''

Then you should be able to access it with any function.
The only time when you need to make a variable global is if you created that variable inside of one function, and then are trying to access it inside of another.

LukeWright (114)

If you don't declare is as Global, then once you change the variable inside a function, It will change back to whatever you initially declared it as as soon as the function is done. no? @InvisibleOne @BrandonBailey3

InvisibleOne (2672)

No @LukeWright

number = 10
print(number) # will get 10 printed
def change_number():
  number = 20
change_number()
print(number) # will print 20
InvisibleOne (2672)

Oh, well I'm an idiot. To fix that just put global number as the first line in the function. @LukeWright