Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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 namex, Python uses the value of the parameter declared in the function.

 

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

 

In the lastprint statement, we confirm that the value ofx in the main block is actually unaffected.