1 Python is Dynamic

Python is dynamically typed. You do not need to declare variables. You may simply assign to them, which creates the variable. Variables may hold simple types (integers, floats, etc.), functions, and objects among other things.

x = 1
name = "sample string"
name2 = 'another sample string'
name3 = """a multiline
  string example"""
y = 3.14
longint = 100000000000L
z = None

Note the last example. Python has a special value called None. It is generally used to represent a null value. Variable names are case sensitive. Variables can change type, simply by assigning them a new value of a different type.

x = 1
x = "string value"

Typing a variable name by itself at the interactive prompt results in its value or information about it being printed out (unless you are in PyRAF and type the name of an IRAF task, in which case CL emulation mode is entered and the task runs with no command-line arguments). Unlike the IRAF CL, no equal-sign (=) is needed to inspect a Python variable:

>>> x = 1
>>> x
1
>>> x+3
4

One exception to the rule is that if the value of the expression is None then nothing is printed.

A common error is to expect the same behavior in Python scripts. In a script nothing will be printed for the above example; if you want a script to print a value, use the print statement. Another common error is to leave off parentheses for a Python function. For example,

>>> raw_input()

reads a line of input from stdin, but if you type

>>> raw_input
<built-in function raw_input>

you are simply inspecting the raw_input variable, which as the message says is a Python built-in function.

Questions or comments? Contact help@stsci.edu
Documented updated on 2002 May 3