9

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user3170915
  • 117
  • 2
  • 7
  • Adding global declarations will not double the length of your code, unless your code is already really short. – BrenBarn Apr 03 '14 at 07:45
  • @BrenBarn I think his function is used to no more than to initialize a set of global configuration parameters. So it seems logic to me that his code `x = 1 y = 3 z = ...` will be almost doubled when having to write a `global var` statement for each initializated variable. – Pablo Francisco Pérez Hidalgo Apr 03 '14 at 07:50
  • @PabloFranciscoPérezHidalgo: If so, making it into a function wouldn't gain anything anyway. – BrenBarn Apr 03 '14 at 07:52

2 Answers2

9

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.

  • Thank you, I didn't know that you could list multiple variables and that definitely helps. It was also my understanding that I would have to use the global statement multiple times on a single variable if I changed the value of the variable multiple times. But now I figured out I only have to do a single global statement for all of the variables and I won't have to use it again even if I change the variable twice. – user3170915 Apr 04 '14 at 06:16
  • Also, it is a bit more than just initializing the variables, it is asking the user what those values should be and using many print lines to make it look nice, that is why I wanted to be able to use a function in the case that I would let the user restart on setting those variables. Thank you both for your answers. – user3170915 Apr 04 '14 at 06:19
2

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.

Community
  • 1
  • 1
ThaMe90
  • 4,196
  • 5
  • 39
  • 64