Variables¶
There are several types of variables:
a = True # Boolean
b = False # Boolean
c = 123 # Integer, range is -32768 to 32767
d = "hello" # String, size limits vary by platform
e = (None, True, 2, "Three") # Tuple – usable only as a constant in SNAPpy
f = None # Python has a "None" data type
g = startup # Function
h = xrange(0, 10, 3) # Iterator (introduced in SNAP 2.6)
i = [1, 1, 2, 3, 5, 8] # Byte List (introduced in SNAP 2.6)
In the above example, invoking g()
would be the same as directly calling startup()
. You can use the
type()
function to determine the type of any variable in SNAPpy.
Variables can change their type on the fly:
x = 99 # variable x is currently an integer (int)
x = False # variable x is now a Boolean value of False
x = "hello" # variable x is now a string (str)
x = (x == "hello") # variable x is now a Boolean value of True
String variables can contain binary data:
A = "\x00\xFF\xAA\x55" # The "\x" prefix means hexadecimal character
B = "Pi\xe1" # This creates a string of length 3
Byte lists allow for updates without rebuilding:
A = [7, 8, 9]
A[2] += 1
Variables at the top of your script are global:
x = 99 # this is a global variable
def sayHello():
print("x=", x)
Variables within functions are usually local:
x = 99 # this is a global variable
def showNumber():
x = 123 # this is a separate local variable
print(x) # prints 123
Unless you explicitly say you mean the global one:
x = 99 # this is a global variable
def showGlobal():
print(x) # this shows the current value of global variable x
def changeGlobal():
global x # because of this statement
x = 314 # this changes the global variable x
def changeLocal():
x = 42 # this statement does not change the global variable x
print(x) # will print 42 but the global variable x is unchanged
Creating globals on the fly:
def newGlobal():
global x # this is a global variable, even without previous declaration
x = x + 1 # ERROR! - variables must be initialized before use
if x > 7: # ERROR! – variables must be initialized before use
pass
These two statements are not errors if some other function has previously initialized a value for global variable
x
before the newGlobal()
function runs. Globals declared in this way have the same availability as globals
explicitly initialized outside the scope of any function.
Note
On RAM-constrained devices, SNAPpy scripts limit the number of concurrent local variables and system global variables. See SNAP Modules for more information on limits.