11/6/09

Really Quick python tutorial (Part I: Intro)

I want to start posting a series of notes about python that can be used by programmers. But note that i have not tried to use the correct syntax.

  •  Integer division returns the floor.  7/3=2   7/-3=-3
  • Complex numbers are supported but "i" turns into "j" or "J". another alternative is: complex(real,imaginary) function.  z.real and z.imag are used for accessing real and imaginary parts. conversion functions such as float() int() and long() don't work for complex numbers.  to get the magnitude of a complex number:abs(z)
  • in interactive mode, the last printed expression is assigned to the variable _. this variable should be treated as read-only by the user. if you assign a value to it explicitly, you would create an independent local variable with the same name masking the built in variable with its magic behaviour.
  • and equivalent to heredoc in php is using a pair of matching triple quotes: """ or '''.
  • string concatenation: +   repeat:*  word="hi"   '<'+word*5 + '>'
  • automatic concatenation: 'hi' 'hello'   = 'hihello'  (can only be used for two string literals
  • string indexing:  word="helpA"  word[4]=A   word[0:2]=He word[2:4]=lp
  • python strings can not be changed by indexing. but:   'x'+word[1:]=xelpA
  • And omitted first index defaults to zero. and omitted second string defaults to size of the string being sliced.
  • s=s[:i]+s[i:]
  • an index that is too large is replaced by the string size.
  • and upper bound smaller that the lower bound returns an empty string.
  • indices may be negative numbers , to start counting from the  right.
  • Out-of-range negative slice indices are truncated. word[-100:]=helpA
  • The indices are pointing between characters. 
  • length of string: len(s)
  • List items need not all have the same type.  a=['spam','eggs',100,1234]   3*a[:3]+['Boe!'] -> ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
  • len(a) to get the length of a list.
  • using nested lists are also possible
Finbonacci series in python(note the multiple assignment):

a,b=0,1
while b<10:
  print b
  a,b=b,a+b