Python Programming - Very Short Tutorial
Python is a high-level object-oriented dynamic programming language which enables very short source code size and best readability / maintainability. Python is especially suitable as embedded scripting language in applications like HarvEX (mp), SynchronEX, 1stCMS, TurboMailer, Turbo Email Answer. Python does well as glue language (via all kinds of interfaces) and it is also a superior main language for large projects .Python code can be executed / tried interactively at the "prompt";
it be executed as script; or it can be imported as module
from other Python code. Python includes a comprehensive
platform-independent standard library for all kinds of basic needs.
Python code is interpreted and auto-compiled on-the-fly. A seamless
transition to static typing (and maximum speed) is possible via Cython.
Python programs can run natively on all major operating systems and in
Java-Runtime-Environment and in .NET/Mono.
The 2 page very short tutorial below will reveal some "90%" of the Python syntax & usage as far as it is necessary for everyday Python scripting. Beyond that you "just" need to learn the special API, the functions and objects relevant for your use case...
Further Reading: Long Python Tutorial, Python Documentation, Python Quick Reference
Note: Python here means Python 2 - not the Py3K
project, which has somewhat incompatible syntax and which is hardly
used in real world projects
Getting started with Python
Interaction at the Python prompt: numbers, strings, tuples and lists
>>> 2 + 2, "text", range(10), sum(range(10)), (1,2+3,(4,5)), 3.0 * 1e-3 / 2, (2 + 2j) ** 2
(4, 'text', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 45, (1, 5, (4, 5)), 0.0015, 8j)
Handling lists:
my_list = ['welcome', 'to', "the", "python world", u"unicode \u1234", '\x01\xFF', 0, 0.0]
print my_list[0], my_list[-2:] # print first and last two elements
print my_list.pop() # pop last element
for x in my_list:
# python code blocks are defined by pure indentation
print x, len(str(x)), type(x)
lst = my_list[:5] # take first 5 elements
a, b, c = lst2 = my_list[1:4]
reverse_list = my_list[::-1]
my_list[5:7] = 1.0, 2.0
print '\t'.join(lst) # joins string list with TAB-spaces
print [s for s in lst if s.startswith('t')] # a list comprehension
print map(string.upper, lst) # string.upper for each element of the list
if isinstance(a, basestring):
print "this is a string or unicode string:", a
Using a dictionary (mapping):
d = {'first' : 1.0, 'second' : 2.0}
d = dict(first=1.0, second=2.0)
if 'first' in d:
print 'yes'
for key in d:
print d[key]
value = d['first'] + d.get('third', 0.0) # .get yields default value 0.0
d[(77, 99)] = 'most object types can be used as dictionary key'
d.clear()
Functions and conditions:
def my_function(a, b=1, c=2): # b=1, c=2 : default arguments
print a, b + c
return "thanks for calling", a + b + c # 2 return values (tuple)
text, result = my_function(7, c=8)
if result < 100 or (result == 600 and text):
print "result '%s' is: %.2f" % (text, result)
elif 200 < result < 300:
while random.random() < 0.9:
print 'looping ...'
if random.random() <= 0.2:
break
else:
print "neither nor"
def use_function(func):
print "its result:", func(0)
use_function(my_function) # functions can be passed like anything else
lst.sort(lambda a, b: -cmp(len(a), len(b))) # sorts list on string length via ad-hoc lambda function
def iter_fibonacci(n=1000):
# a generator function yields iteratively
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
for x in iter_fibonacci():
print x,
Using classes:
class X:
a = 1
def __init__(self, c=0.0): # auto-called when object is created
self.lst = [1, 2, 3]
self.c = c
def f(self):
return self.a * 2 # self is the object itself
class Y(X): # class Y inherits from X
b = 2
def f(self, v, *args, **kwargs): # extra positional args and keyword kwargs
print v, "more args:", args, kwargs
self.value = v # new attribute "value" created on-the-fly
return self.a * 3
y = Y() # creates an Y object
print y.f(1.0, 2, 'text', extraarg='extra') # calls its method f
print getattr(y, 'value', 0.0) # yields 0.0 if attribute 'value' is not existing
Modules, math and regular expressions:
import re, os, glob, thread, encodings.ascii
from math import *
print re.search(r"#(\d+)", "is #123 a number?").group(1)
# sinus, power, modulo, bit-or/and, logic-or/and, bit-xor, unequal
print sin(1.8**2 % 3), 1 | 2 & 7, 0 or 1 and 2, 1 ^ 3, 1 != 3
Handling exceptions and enforcing finalization:
try:
try:
y = 1 + 2 / int(open('file.txt').read())
finally:
print "file processed" # executed no matter what problem happened
except ZeroDivisionError:
print "zero division!"
raise # re-raises this ZeroDivisionError
except (IOError, ValueError), evalue:
print "file parsing error:", evalue
else:
# only executed when no error
print "result successfully computed:", y