Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions access to global variables

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?

like image 791
user3170915 Avatar asked Apr 03 '14 07:04

user3170915


People also ask

How do you pass a global variable in a function?

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.

Can functions in Python access global variables?

You can access global variables in Python both inside and outside the function.

Can functions access global variables C?

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.

Can functions access global variables JavaScript?

A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.


2 Answers

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.

like image 160
Pablo Francisco Pérez Hidalgo Avatar answered Oct 13 '22 21:10

Pablo Francisco Pérez Hidalgo


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.

like image 2
ThaMe90 Avatar answered Oct 13 '22 22:10

ThaMe90