Use Local Variables In Python Scripts

Python local variables help reduce programming bugs.

Just as highway medians separate opposing traffic, Python’s name-space conventions prevent unintended program collisions by controlling when and where variables are accessed. A “local” variable is declared within a function and is accessible only within that function. In order to make a variable accessible outside of the function, it must first be declared “global”. Local variable names are unique to the function in which they are used. The value pointed to by a local variable name can be made accessible with the Python “return” statement.

Instructions

1. Launch the standard, plain-text text editor application that is available on your computer.

2. Enter the following code into the text editor exactly as shown below. Python is case-sensitive. In addition, blank spaces and indentation have significance in Python. Replace the “^” symbol with a blank space.

print

print

x = “yellow”

print “Programmer: Your color is ” , x

def myColor(x):

^^print “Python: I know you say my color is ” , x

^^x = “aubergine”

^^print “Python: But my actual color is ” , x

^^return

myColor(x)

print “Programmer: No! Your color is “,x, ” but I will change it to green”

x=”green”

myColor(x)

3. Click on the “File” menu and select “Save”. Name the file “localvalue.py”.

4. Click the “File” menu then select the appropriate option to close the text editor.

5. Launch the system terminal, console, or command line. At the command line prompt, type “python” then press the enter key.

6. Type execfile(“localvalue.py”) at the Python command prompt then press the enter key.


READ  Become An Architectural Cad Technician