Tutorial

Strings

Strings in Python are much like strings in C, in that they can be references either as the full string or treated as a character array.

>>> d = "Hello"
>>> d
'Hello'
>>> d[ 4 ]
'o'
>>> d[ 1:4 ]
'ell'

Strings can also be iterated over like a sequence.

>>> for i in d:
	print i
H
e
l
l
o
>>> list( d )
['H', 'e', 'l', 'l', 'o']

Dynamic Typing and Type Checking

Unlike many computer languages, Python does not have static variable types. Types are dynamic, meaning they are changed on an as-needed basis. This can sometimes create problems, but is usually only problematic when creating public libraries, where the input types to a function cannot be controlled. The type( ) function can be used to determine the type of an object.

>>> g = 4
>>> type( g )
<type 'int'>
>>> g = 4L
>>> type( g )
<type 'long'>
>>> g = "Hello"
>>> type( g )
<type 'str'>

Lists , Tuples, and Dictionaries

There are 3 major types of sequence types in Python. These, as I'm sure you can tell from the title, are the list, the tuple, and the dict (dictionary). These correspond to types in many other languages, lists and tuples are like normal arrays, dictionaries are like associative arrays.

Loops and Iterators

Unless you are new to programming, you have doubtlessly seen and used many loops. In Python, the while loop is just like any other language, though parentheses are optional:

sum = 0
i = 0
while ( i < 10 ):
    sum += i
    i += 1

print sum

This would sum the numbers 0 through 9, which is 45.

Importing Modules

Like many languages, Python has a basic set of functions and objects available to it to start off with, but to really use the power of the language, you'll need to import modules or packages from the library. I won't get into the difference between the two here, but from a usage perspective, there isn't one. From this point forward I will refer to both as modules.

There are two basic ways to import modules in python:

import math
#or
from math import *

Powered by Drupal - Design by artinet