Python Datatypes

Strings, Numbers, and Booleans

Literal strings can be typed in using either double quotes or single quotes. This can be handy when your string contains one quote or the other. You can also use the backslash character to escape special characters. Strings that contain characters beyond 7-bit ASCII, such as é or щ need to be marked as unicode strings by placing the letter u in front of the string. There is no harm in marking all strings as unicode strings. The following prints a unicode string:

Unicode Example
print u'été'

The None Value

There is a special value in Python called None (with a capital N). This is simply a special value that means: no value. This value is equivalent to Java's null value.

None Example
# Create a None value and test for it
var = None
if var == None:
print 'Variable has a value'
else:
print 'Variable is None'


List

In Python, lists (arrays) are a built-in type that contains multiple other values. Lists can contain any type of items, and the items in a list do not all need to be the same type. You can create a list by enclosing multiple items in square brackets ([]), separated with commas. You can pull items out of a list with the square-bracket list index notation. Note that lists are zero-indexed, meaning that the first item in the list is at position 0. This code will print out "a list".

List Example
# Create a list, then step through it and print each item to the console
myList = [1, 2, 'abc', [1, 3]]
for item in myList:
print item


Basic Operators

Python has all of the normal arithmetic operators you'd expect, addition(+), subtraction(-), division(/), multiplication(*), modulus(%), etc.

The comparison operators are just like in C: equals(==), not equals(!=) greater than (>), greater than or equal(>=), etc.

The logical operators are just typed in plain text: and, or, not.

These are just the basics. There are other operators, like bit shift operators. Read about them at: http://docs.python.org/library/stdtypes.html

Operators Example
# test a few values
x = 5
y = 12
if x == y:
print 'They match'
elif x > y:
print 'x > y'
else:
print 'x < y'

White Space

Perhaps its most unique feature, logical blocks are defined by indentation in Python. A colon (:) starts a new block, and the next line must be indented (typically using a tab of 4 spaces). The block ends when the indentation level returns to the previous level. For example, the following will print out "5 4 3 2 1 Blast-off". The final print is not part of the loop, because it isn't indented.

countdown=5
while countdown > 0:
print countdown,
countdown = countdown - 1
print "Blast-off!"