A Byte of Python

Local Variables

When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.

Using Local Variables

Example 7.3. Using Local Variables

				
#!/usr/bin/python
# Filename: func_local.py

def func(x):
	print 'x is', x
	x = 2
	print 'Changed local x to', x

x = 50
func(x)
print 'x is still', x
				
				

Output

				
$ python func_local.py
x is 50
Changed local x to 2
x is still 50
				
				

How It Works

In the function, the first time that we use the value of the name x, Python uses the value of the parameter declared in the function.

Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x defined in the main block remains unaffected.

In the last print statement, we confirm that the value of x in the main block is actually unaffected.

Using the global statement

If you want to assign a value to a name defined outside the function, then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.

You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is. Using the global statement makes it amply clear that the variable is defined in an outer block.

Example 7.4. Using the global statement

				
#!/usr/bin/python
# Filename: func_global.py

def func():
	global x

	print 'x is', x
	x = 2
	print 'Changed global x to', x

x = 50
func()
print 'Value of x is', x
				
				

Output

				
$ python func_global.py
x is 50
Changed global x to 2
Value of x is 2
				
				

How It Works

The global statement is used to decare that x is a global variable - hence, when we assign a value to x inside the function, that change is reflected when we use the value of x in the main block.

You can specify more than one global variable using the same global statement. For example, global x, y, z.