Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function global variables?

I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)

x = "somevalue"  def func_A ():    global x    # Do things to x    return x  def func_B():    x = func_A()    # Do things    return x  func_A() func_B() 

Does the x that the second function uses have the same value of the global copy of x that func_a uses and modifies? When calling the functions after definition, does order matter?

like image 880
Akshat Shekhar Avatar asked May 14 '12 17:05

Akshat Shekhar


People also ask

Can you use global variables in a function Python?

Global variables can be used by everyone, both inside of functions and outside.

How do you pass a global variable to a function in Python?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

How do you access a variable inside a function in Python?

The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.


1 Answers

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar someVar = 55 

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

like image 193
Levon Avatar answered Oct 28 '22 23:10

Levon