![]() |
|
global variables - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Python (https://sinister.li/Forum-Python) +--- Thread: global variables (/Thread-global-variables) |
global variables - J4W3S - 03-28-2013 hey, not sure if this will be of any use but it took me a while to find out how to do make global variables in python and i think this is the easiest way. First off make a config.py file this will hold all of your global variables so you can use them later in your other modules. Config Code: name = ' '
age = 0
# you can add what ever variables you need to herethen all you need to do is import this file at the start of any modules you will be using these global variables in. Code: import config # loads all variables from the config module
print (config.name) # will print the variable from config
config.name = input('what is your name') # this will edit the variable in the config moduleSo basically after you have imported the config module you can use the variables from it as you would normally, as long as you remember to put the config. in front of the variable name. p.s. the module can be called anything just make sure that you keep the name same throughout. e.g. if your config file was called global.py you would import global and use the global.(your variable) RE: global variables - Ex094 - 03-28-2013 You can also set a Variable to Global using the global statement in python (I'm using 3.3) Code: global your_variable_nameFor more understanding visit http://zetcode.com/lang/python/functions/ RE: global variables - DaPaus - 04-03-2013 I'm using Python 2.7.3 and you can easly just put global in front of it example: Code: var = 10 #makes a variable outside any function
def func():
global var #calls the global variable "var"
print var + var #uses the variable in a calculation and prints out the value
var = var + 5 #Change the value if global variable var
calc()
print var #shows that the variable is changed by the functionThis code gives as outcome number 20 (var+var) and number 15 (var + 5) Hope I helped |