Local Variables


A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

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.