![]() |
![]() |
|
|||||||||||||||||||||||||||
![]()
Python is the state-of-the-art very-high-level object-oriented (script) programming language heading for shortest code size and readability without compromises. Python is especially strong as embedded language (sandbox) in applications and as glue language.
Python code can be executed interactively ( ">>>" prompt ) or can be executed from script or can be imported as modules from files.
Python code is interpreted and auto-compiled on-the-fly.
Getting started:
Interactive session with an interpreter: numbers, lists and tuples ( interactive prompt ">>>" ) :
>>> 2+2, range(10), (1,2,3), 1.0, 1e-3, 2+2j
(4, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], (1, 2, 3), 1.0, 0.001, (2+2j))
Looping over lists:
my_list = ['welcome',"to",'the','python','world']
print my_list[0], my_list[-2:], my_list.pop() # print first and last two elements, pop last
for x in my_list:
print x, len(x), type(x) # python code blocks are defined by indentation
print '\t'.join(my_list) # joins string list with TAB-spaces
print [ s for s in my_list if s.startswith('t') ]
print map( string.upper, my_list ) # string.upper each element of the list
Defining and using a python dictionary (a "mapping"):
d = { 'first' : 1.0 , 'second' : 2.0 }
if 'first' in d: print 'yes'
for ix in d: print d[ix]
value=d['first'] + d.get('third',0.0) # .get yields default value 0.0
d[(77,99)]='most types/objects 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 ) # c=8 : keyword argument
my_list.sort( lambda a,b:-cmp(len(a),len(b)) ) # lambda (ad-hoc) function for sorting on string length
if 0<result<100:
print "result '%s' is:%.2f" % (text,result)
elif result>500:
while random.random()<0.9:
print 'looping ...'
else:
print "hmm..."
Defining and using a class:
class X:
a=1
def f(self): # self
return self.a * 2
class Y(X): # Y inherits from X
b=2
def f(self,value,*args,**kwargs): # extra positional args and keyword kwargs
print value,"var args:",args,kwargs
self.value=value # new attribute "value" created on-the-fly
return self.a
y=Y(); print y.f( 1.0,2,'text', happyarg='happy' )
Modules, math and regular expressions:
import re,os,glob,thread,encodings.ascii
print re.search( r"#(\d+)", "is #123 a number?").group(1)
from math import *
print sin( 1.8**2 % 3 ), 1|2, 1 or 2, 1^3 # sinus, to-the, modulo, bit-or, logic-or, bit-xor
We can't really show Pythons limits in this tutorial:
try: y.value + 1/0
except AttributeError,v: print "attribute missing:",v
except ZeroDivisionError: print "ZERO!"; raise
def no_delay_files_lines():
""" generator function : 'yield' returns iterated values on-the-fly
lookup this doc string by help(no_delay_files_lines) """
for filename in glob.glob("hugedata/*.txt"):
if os.path.isfile(filename):
for line in open(filename):
yield line.strip() and line[:-1] or "<empty line>"
for line in no_delay_files_lines(): print line
thread.start_new(my_function,(1,2,3))
print "methods:", [ var for var in dir(y) if isinstance(getattr(y,var),types.MethodType) ]
y.__dict__.update(d)
print "instance_dict:", y.__dict__,y.first,y.value==y.__dict__['value']
class Z(Y,list,object):
"python classes can be types and can be derived from base types"
def __mul__(self,other): # define a 'mul' (*) operator for Z class instances
return [a*b for a,b in zip(self,other)]
def ff():return "ZZZ"
ff=staticmethod(ff)
Z.smart_slot = property( lambda self:self.a+len(self), Y.my_method )
Y.__bases__=()
Z.__metaclass__=...
...
webmaster@xellsoft.com
- © 2010 Xellsoft.com. All Rights Reserved
- Online Privacy - Affiliate
- Company