hi all type -a python{,w,2.3,2.4,2.5} fink list python24 ipython [ -f /sw/bin/init.sh ] && source /sw/bin/init.sh less ~/.bashrc source ~/.bashrc fink install ipython-py24 Notes: ------- type() gives you the type of an entitiy. ''' /// ''' Spans multiple lines. Set a variable: In [10]: aStr="some old string" In [11]: aStr Out[11]: 'some old string' # Index a variable. A string is an array. Index with brackets. In [12]: aStr[0] Out[12]: 's' # A slice of an array. In [13]: aStr[5:8] Out[13]: 'old' # Index from the back. In [14]: aStr[5:-1] Out[14]: 'old strin' # To get a list of methods for an object type object. # Remember to add () to the methods, since they're functions. aStr.islower() Out[20]: True # Replace characters In [22]: aStr.replace('i','*') Out[22]: 'some old str*ng' # Note print evaluates things like \t In [23]: aStr Out[23]: 'some old string' In [24]: aStr.replace('o','\t') Out[24]: 's\tme \tld string' In [25]: print aStr.replace('o','\t') s me ld string In [26]: print "hello world" hello world In [27]: print "hello","world" hello world # Note how to concatinate strings. You can't embed aStr within the quotes # and have it interpreted. In [29]: print "before "+aStr+ " after" before some old string after # Find finds the first occurance of a character In [31]: aStr.find('d') Out[31]: 7 # But it it doesn't find it, you get a -1. In [32]: aStr.find('x') Out[32]: -1 # To find out about a function, append a '?' In [33]: aStr.find? Type: builtin_function_or_method Base Class: String Form: Namespace: Interactive Docstring: S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. # To split a line on white space (default delimter): In [34]: aStr.split() Out[34]: ['some', 'old', 'string'] # Make a string with comma delimiters: In [35]: anotherStr='10,20,30,405,something' In [37]: anotherStr.split(',') Out[37]: ['10', '20', '30', '405', 'something'] # Assign the resulting list in a variable. In [38]: aList=anotherStr.split(',') In [39]: aList[2] Out[39]: '30' # Lists are Arrays. In [41]: newList=[] # You can even have lists of lists in python. In [39]: listoflist = [ [1,2,3], 'two'] In [40]: print listoflist [[1, 2, 3], 'two'] # Append with a list as the argument, inserts the list as a single new item. In [43]: newlist=['a','b'] In [45]: newlist.append(aList) In [46]: newlist Out[46]: ['a', 'b', ['10', '20', '30', '405', 'something']] # But to append a list onto a list use a "+" In [47]: newlist+aList Out[47]: ['a', 'b', ['10', '20', '30', '405', 'something'], '10', '20', '30', '405', 'something'] # See how range works: In [48]: range(2,4) Out[48]: [2, 3] In [49]: range(2,5) Out[49]: [2, 3, 4] In [50]: range(0,10,2) Out[50]: [0, 2, 4, 6, 8] # Check out this cool way to make an array: List comprehension In [51]: [ x*.1 for x in range(2,15,3) ] Out[51]: [0.20000000000000001, 0.5, 0.80000000000000004, 1.1000000000000001, 1.4000000000000001] # Math functions: In [51]: import math In [52]: math. math.__class__ math.__str__ math.frexp math.__delattr__ math.acos math.hypot math.__dict__ math.asin math.ldexp math.__doc__ math.atan math.log math.__file__ math.atan2 math.log10 math.__getattribute__ math.ceil math.modf math.__hash__ math.cos math.pi math.__init__ math.cosh math.pow math.__name__ math.degrees math.radians math.__new__ math.e math.sin math.__reduce__ math.exp math.sinh math.__reduce_ex__ math.fabs math.sqrt math.__repr__ math.floor math.tan math.__setattr__ math.fmod math.tanh # To put everything in the upper level name space you can execute from math import * # So now you don't have to type math. (e.g. math.pi). You can just # type "pi". But this will clobber functions in the upper name space that # have the same name. # You could however just pull in one function at a time from math import pi # No complex numbers for sqrt In [58]: math.sqrt(-1) Out[58]: nan # But complex numbers are generally built in. In [59]: 2+3j Out[59]: (2+3j) # To get just the imaginary part: In [62]: a=(2+3j)*(3-3j) In [63]: a.imag Out[63]: 3.0 # To handle floating point numbers and not get odd bit rounding, use the # decimal module. It has an object called Decimal that you can use for floats # that will look more reasonable. import decimal decimal.Decimal(".1")+3 Out[75]: Decimal("3.1") # Note the Decimal object here is a number that you can add other things to. # Type conversions: # to convert to ints: int(string) # To convert to strings: str(num) # To convert to a float: float(string) # If you're parsing data in a file, those will come in very handy, because # everything will be read in as strings. You'll have to convert numbers to # the appropriate type. # Conditionals (ifs) In [79]: if 1<2: print 'yes' ....: else: print 'no' ....: yes # or In [80]: if 1<2: ....: print 'yes' ....: else: ....: print 'no' ....: ....: yes # Indenting is CRITICAL: In [81]: if 1<2: ....: print 'yes' ....: print 'error' ------------------------------------------------------------ IndentationError: unindent does not match any outer indentation level (, line 3) # Booleans are capitalized In [82]: print (1<2) True In [83]: print (1>2) False In [84]: print (1==2) False # For Loops: # using our range command In [85]: for i in range(2,9): ....: print i ....: 2 3 4 5 6 7 8 # Continue in a loop: NameError: name 'x' is not defined In [88]: for i in range(1,10): ....: if i==5: continue ....: print i ....: ....: 1 2 3 4 6 7 8 9 # Looping over a list: In [92]: for z in ['one', 2,'three']: ....: print type(z),'---->', z ....: ....: ----> one ----> 2 ----> three # ipython can do shell stuff: In [93]: pwd Out[93]: '/Users/vschmidt' In [94]: cd /Users/vschmidt/svnsandbox/python_misc/trunk/ /Users/vschmidt/svnsandbox/python_misc/trunk In [95]: ls myfile.txt test.py In [96]: pwd Out[96]: '/Users/vschmidt/svnsandbox/python_misc/trunk' # Reading from a file: # "open" and "file" are the same thing. But you never use "open" In [97]: for line in file('myfile.txt'): ....: print line ....: ....: First line 2nd line etc # But notice that you get an extra \n for each line. # To "chomp" (that's a perl thing) the \n off the end, add a comma In [98]: for line in file('myfile.txt'): ....: print line, ....: ....: First line 2nd line etc # Print puts a \n at the end of everything you print by default. To # NOT print the \n, append a comma to your print statement. In [99]: print 1,; print 2,; print 3, 1 2 3 In [100]: print 1,; print 2,; print 3 1 2 3 In [101]: print 1,; print 2; print 3 1 2 3 # Here we make a file in the bash shell: valsmac:~/svnsandbox/python_misc/trunk vschmidt$ cat << EOF > my.dat > 1 2 > 3 4 > 1.2 3.4 > EOF # Here we open a text file, read in the values and add them rowwise: In [104]: for line in file('my.dat'): .....: fields=line.split() .....: total = float(fields[0]) + float(fields[1]) .....: print total .....: .....: 3.0 7.0 4.6 # To get the time: import datetime In [119]: datetime.datetime.utcnow() Out[119]: datetime.datetime(2006, 10, 31, 15, 52, 26, 383943) # To get the month: datetime.datetime.utcnow().month # To add or subtract time: In [123]: datetime.datetime.utcnow() + datetime.timedelta(days=1) Out[123]: datetime.datetime(2006, 11, 1, 15, 55, 12, 631363) In [124]: datetime.datetime.utcnow() + datetime.timedelta(days=-1) Out[124]: datetime.datetime(2006, 10, 30, 15, 55, 19, 264891) # The time module: import time # To sleep time.sleep(3) # Help for modules: help(datetime) Then bring up the URL in a browser for better documentation of the module. # Writing to a file: # Opening a file for writing (over-writing actually) In [157]: out = file('out.dat','w') # Writing to the file: In [158]: for i in range(10): .....: time.sleep(1.1) .....: t=datetime.datetime.utcnow() .....: timeStamp=str(time.mktime(t.timetuple())) .....: out.write(str(i)+' '+str(math.sin(i/4.0))+' '+str(timeStamp)+'\n') .....: .....: In [160]: out.close() # NOTE the data is not actually written until you close the file. # LOOK OUT FOR INTEGER DIVISION In [151]: 1/4 Out[151]: 0 In [152]: 1/4.0 Out[152]: 0.25 In [153]: 1/4. Out[153]: 0.25 From Kurt filename = 'out.dat' iterations=10 stepSize=1.1 out = file(filename,'w') for i in range(iterations): time.sleep(stepSize) t = datetime.datetime.utcnow() timeStamp = str(time.mktime(t.timetuple())) out.write(str(i)+' '+str(math.sin(i*stepSize))+' '+timeStamp+'\n') # gnuplot aside: # To plot 3-column data in 3D plot (in this case with time on third axis). # within gnuplot splot "out.dat" with lp # How to write a python script: #!/usr/bin/env python # This uses the first python of all of them listed on this machine, # specified in your path. This is the safe way to build a script. # Remember don't use "which" to figure out what's in your path, use this # instead: vschmidt$ type -a python python is /sw/bin/python python is /usr/bin/python # So the one in /sw/bin/python will be executed.