I am working on a text-based game to get more practice in Python. I turned my 'setup' part of the game into a function so I could minimize that function and to get rid of clutter, and so I could call it if I ever wanted to change some of the setup variables.
But when I put it all into a function, I realized that the function can't change global variables unless you do all of this extra stuff to let python know you are dealing with the global variable, and not some individual function variable.
The thing is, a function is the only way I know of to re-use your code, and that is all I really need, I do not need to use any parameters or anything special. So is there anything similar to functions that will allow me to re-use code, and will not make me almost double the length of my code to let it know it's a global variable?
Both local and global variables are passed to functions by value in C. If you need to pass by reference, you will need to use pointers.
You can access global variables in Python both inside and outside the function.
Use of the Global Variable in C As already stated earlier, any function can access a global variable. It means that once you declare a program, its global variable will be available for use throughout the running of the entire program.
A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.
You can list several variables using the same global
statement.
An example:
x = 34
y = 32
def f():
global x,y
x = 1
y = 2
This way your list of global variables used within your function will can be contained in few lines.
Nevertheless, as @BrenBarn has stated in the comments above, if your function does little more than initializating variables, there is no need to use a function.
Take a look at this.
Using a global variable inside a function is just as easy as adding global
to the variable you want to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With