Now
that we have seen how a simple CGI program works, let's inspect how
variables work in Python. All assignments have the syntax identifier = value.
Identifier names can be begin with either an underscore or letter
followed by any combination of letters, numbers, and underscores.
In addition, names are case sensitive (i.e., name is different from Name). Variables have dynamic type in Python, so there is no need to specify types in declarations [4].
Table 2.1 shows the variable types of Python with examples of each.
The code examples below demonstrate various assignment methods and results.
Code Example 2.1:
#!/usr/bin/python
# Print the required header that tells the browser how to render the text.
print "Content-Type: text/plain\n\n"
# Initialize a few variables.
first = 5
middle = 7.5
last = 10
# Print the values.
print "first:", first
print "middle:", middle
print "last:", last
Multiple assignments can be done at once. Python handles a = b = c assignments in a right associative manner. In addition, Python performs a swap operation on the assignment:
or
and
not
==, !=, <, <=, >, >=, <>
in, not in
+, -
*, /
%
a[i], a[i:n], a.b
Logical OR
Logical AND
Logical NOT
Comparison
Sequence Membership
Addition/String Concatenation, Subraction
Multiplication/String Repetition, Division
Modulus
Indexing, Slicing, Qualification
Code Example 2.3 demonstrates the functionality of a few of the
operators above. Pay close attention to the dynamic typing as a
result of integer and decimal value calculations. Note that specifying
a negative index works like counting back from the end of the string.
Code Example 2.3:
#!/usr/bin/python
# Print the required header that tells the browser how to render the text.
print "Content-Type: text/plain\n\n"
# Integer division resulting in a truncated value.
a = 5/2
# Print parts of the string.
print "The first character is:", python_words[0]
print "The last character is:", python_words[-1]
print "In the middle is: \n", python_words[1:-1]
So
far, we have covered numbers and strings fairly well. As we use
more advanced features of the Python language, we will demonstrate the
capabilities of lists, dictionaries, tuples, and files.