Saturday, September 19, 2009

Python Tutorial

CPythonImage via Wikipedia

I've been learning Python and here is what I have learned so far:

1. Python is a scripted language

2. In Python, indentation matters because it's how logic blocks are grouped together

3. Python is not strongly typed like C++, C#, and Java

4. Python has the following data types - dynamic

a. Lists - dynamic array can be appended, sorted, and all kinds of goodies; defined by []

b. Tuples - array that can't be changed

c. Dictionaries - ie {'key': 'value', 'a' : 'b'}, d['k'] = 'v‘

d. integer

e. float

f. string

g. Special statements
i pass,del, raise, assert, exec
ii global
iii break
iv continue
v try
5. For loops
for item in sequence:
Statements

else:
statements


– Example:

for item in (1,3,5,7,9,15,2003):
print item

for item in xrange (1, 50):
sum += item


6. While loops
While ... [else]
while a == b:
work ()

else:
finalize ()


7. If statements
If ... [elif ... else]
if a == c:
print “a equals c”

else:
print “a and c are different”


8. Functions and Procedures
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements

return # from procedure
return expression # from function

9. Exception
def foo(x):
return 1/x

def bar(x):
try:
print foo(x)
except ZeroDivisionError, message:
print "Can’t divide by zero:", message

bar(0)

10 File Input/output

f = open(filename[, mode[, buffersize])
mode can be "r", "w", "a" (like C stdio); default "r"
append "b" for text translation mode
append "+" for read/write open
buffersize: 0=unbuffered; 1=line-buffered; buffered

methods:
read([nbytes]), readline(), readlines()
write(string), writelines(list)
seek(pos[, how]), tell()
flush(), close()
fileno()

Some links to examples in Python
Simple Sample Python Code
Python Recipes

Reblog this post [with Zemanta]

No comments: