print 'False and False =',False and False print 'False and True =',False and True print 'True and False =',True and False print 'True and True =',True and True print 'False or False =',False or False print 'False or True =',False or True print 'True or False =',True or False print 'True or True =',True or True print 'not False =',not False print 'not True =',not True # nand test: # see http://en.wikipedia.org/wiki/Logical_NAND # (A nand B) is not (A and B) ABList = [(False,False),(False,True),(True,False),(True,True)] for A,B in ABList: print '%s nand %s ='%(str(A),str(B)),not (A and B) print True or False print 1 or 0 print bool(1 or 0) whatTheySay = True if whatTheySay: print "it's true what they say ..." else: print "it's not true what they say ..." whatTheySay = 1 if whatTheySay: print "it's true what they say ..." else: print "it's not true what they say ..." 3 == (1 * 2**1) + \ (1 * 2**0) print bin(3) print 0b11 101 == (1 * 2**6) + \ (1 * 2**5) + \ (0 * 2**4) + \ (0 * 2**3) + \ (1 * 2**2) + \ (0 * 2**1) + \ (1 * 2**0) print bin(101) ''' Explorations in binary! We can represent: binary numbers, e.g. 0b010101 octal numbers, e.g. 0o755 hexadecimal, e.g. 0x2A2FF but if we print these, by default they are printed as the decimal equivalents. We can convert to binary, octal or hex string with bin(), oct(), hex() ''' x = 0b111101101 print bin(x),'is',x,'in decimal' print bin(x),'is',oct(x),'in octal' print bin(x),'is',hex(x),'in hexadecimal' ''' Bitwise operators: ''' A = 521 B = 523 # print as binary: print A,'\tA:\t',bin(A) print B,'\tB:\t',bin(B) # some operations print '\tA | B:\t',bin(A|B),'\t',A|B print '\tA ^ B:\t',bin(A^B),'\t\t',A^B print '\tA & B:\t',bin(A&B),'\t',A&B ''' Bitwise shift operators: ''' A = 531 print '\tA:\t',bin(A),'\t',A print '\tA>>1:\t',bin(A>>1),'\t',A>>1 print '\tA>>1:\t',bin(A<<1),'\t',A<<1 print '\tA>>3:\t',bin(A>>3),'\t',A>>3 print '\tA>>3:\t',bin(A<<3),'\t',A<<3 # an example QA value: fill all fields qa = 0b11111111 print 'qa',qa print 'binary qa',bin(qa) # set up masks for the different parameters mask1 = 0b00000001 # bit 0 mask2 = 0b00000010 # bit 1 mask3 = 0b00000100 # bit 2 mask4 = 0b00011000 # bit 3-4 mask5 = 0b11100000 # bit 5-7 qa1 = qa & mask1 qa2 = qa & mask2 qa3 = qa & mask3 qa4 = qa & mask4 qa5 = qa & mask5 print 'qa1',bin(qa1) print 'qa2',bin(qa2) print 'qa3',bin(qa3) print 'qa4',bin(qa4) print 'qa5',bin(qa5) qa1 = (qa & 0b00000001) >> 0 # bit 0 qa2 = (qa & 0b00000010) >> 1 # bit 1 qa3 = (qa & 0b00000100) >> 2 # bit 2 qa4 = (qa & 0b00011000) >> 3 # bit 3-4 qa5 = (qa & 0b11100000) >> 5 # bit 5-7 print 'qa1',bin(qa1) print 'qa2',bin(qa2) print 'qa3',bin(qa3) print 'qa4',bin(qa4) print 'qa5',bin(qa5) a = 1 b = 0 print a/b a = 1 b = 0 ''' What do we want to happen if we try to divide by zero? In this case, we decide we want to set the result to zero ''' try: print a/b except ZeroDivisionError: print 0 x = 100. del x try: print x except NameError: print "name 'x' is not defined" try: print '2' + 2 # adding a string to integer doesn't make sense except: print 'you made an error' import sys filename = 'files/data/progress.dat' try: f = open(filename) s = f.readlines() print s[0] print s[0]/10 except IOError as e: # trap a specific IOError print "I/O error reading from %s"%(filename) except: # trap any further errors print "Error in processing data from file %s"%filename # We can use separators other than whitespace with split: data = "1964,1220\n1974,2470\n1984,2706\n1994,4812\n2004,2707" print "data.split('\\n'):\n\t",data.split('\n') # note '\\n' in here as '\n' would have printed a newline # \ is an escape character (as in unix) # using a generator expressions fdata1 = (i.split() for i in data.split('\n')) print list(fdata1) # two listcomps to split first # on \n and then each of these on comma fdata1 = [i.split() for i in data.split('\n')] fdata2 = [j[0].split(',') for j in fdata1] print fdata2 fdata1 = [i.split() for i in data.split('\n')] fdata2 = [j[0].split(',') for j in fdata1] fdata = [[int(l) for l in k] for k in fdata2] print fdata # or all at once, which works # but now the meaning of code is too obscure # so this is poor style fdata = [[int(l) for l in k] for k in [j[0].split(',') \ for j in [i.split() for i in data.split('\n')]]] print fdata # It might be comprehensible if laid out better fdata = [[int(l) \ for l in k] \ for k in [j[0].split(',') \ for j in [i.split() \ for i in data.split('\n')]]] # even so you might find this confusing # and prefer to do it is smaller chunks print fdata print "%20s %s"%('hello','world') print "%-20s %s"%('hello','world') pi = 3.1415926536 for format in ["%3.2f","%3.20f","%9.5f","%020.3f"]: print format,'\n\t:',format%pi pi = 3.1415926536 for format in ["%3.2e","%3.20e","%9.5e","%020.3e"]: print format,'\n\t:',format%pi i = 100 for format in ["%i","%3i","%5i","%08i"]: print format,'\n\t:',format%i print "Hey {1}, Hello {0}".format('world','you') print '{0}{1}{0}'.format('abra', 'cad') # date formatting is a particular example from datetime import datetime print """ At the third stroke, it will be {:%Y-%m-%d %H:%M:%S} Beep Beep Beep """.format(datetime.now(),'beep') # character print "char: %c %c %c"%(100,101,102) # octal print "octal: %o"%(0o755) # hex print "hex: %X"%(0xFFF) print "hex: %x"%(0xFFF) # example, with directory names # glob unix style pattern matching for files and directories import glob # returns a list (or [] if empty) # to match the pattern given file_list = glob.glob("files/data/*.txt") print "file_list:\n\t",file_list # e.g. the first string in the list this_file = file_list[0] # split the filename on the field '/' print "\nthis_file.split('/'):\n\t",this_file.split('/') # so the filename is just the last element in this list print "\nthis_file.split('/')[-1]:\n\t",this_file.split('/')[-1] from os import sep # import the string sep from the module os print "On this system, the file separator is",sep # example, with directory names # glob unix style pattern matching for files and directories import glob from os import sep # returns a list (or [] if empty) # to match the pattern given file_list = glob.glob("files{0}data{0}*.txt".format(sep)) print "file_list:\n\t",file_list # e.g. the first string in the list this_file = file_list[0] # split the filename on the field '/' or '\' (sep) print "\nthis_file.split({0}):\n\t".format(sep),\ this_file.split(sep) # so the filename is just the last element in this list print "\nthis_file.split({0})[-1]:\n\t".format(sep),\ this_file.split(sep)[-1] import ephem from ephem import Sun, Observer from math import pi from datetime import date,datetime,time # radians to degrees rtod = 180./pi # observer information in pyephem obs = Observer() today = date.today() # or datetime.date(2013, 3, 12) # put in lat / lon for UCL # https://www.google.co.uk/search?q=ucl+longitude+latitude obs.lat = '51.5248' obs.long = '-0.1336' for hour in xrange(0,24): for minute in xrange(0,60,30): t = time(hour, minute, 0) obs.date = datetime.combine(today, t) sun = Sun(obs) zenith_elevation = float(sun.alt)*rtod # degrees print obs.date,zenith_elevation from ephem import Sun, Observer from math import pi from datetime import date,datetime,time filename = 'files/data/elevation.dat' try: fp = open(filename,"w") except: print "Failed to open file %s for writing"%filename # radians to degrees rtod = 180./pi # observer information in pyephem obs = Observer() today = date.today() # or datetime.date(2013, 3, 12) # put in lat / lon for UCL # https://www.google.co.uk/search?q=ucl+longitude+latitude obs.lat = '51.5248' obs.long = '-0.1336' for hour in xrange(0,24): for minute in xrange(0,60,30): t = time(hour, minute, 0) obs.date = datetime.combine(today, t) sun = Sun(obs) elevation = float(sun.alt)*rtod # degrees fp.write("%s %s\n"%(obs.date,elevation)) fp.close() # just for interest, let's plot this: import pylab as plt %pylab inline filename = 'files/data/elevation.dat' fp = open(filename,"r") hours = [] zeniths = [] for i in fp.readlines(): data = i.split() time = [float(i) for i in data[1].split(':')] hour = time[0] + time[1]/60. + time[2]/(60.*60) zenith = 90. - float(data[2]) if zenith <= 90.: hours.append(hour) zeniths.append(zenith) fp.close() # plotting fig = plt.figure(figsize=(14, 6)) plt.plot(hours,zeniths) plt.xlabel('hour') plt.ylabel('solar zenith / degrees') import urllib2 #as files url = "http://www.metoffice.gov.uk/hadobs/hadukp/data/monthly/HadSEEP_monthly_qc.txt" req = urllib2.Request ( url ) raw_data = urllib2.urlopen(req).readlines() print raw_data[:6] fp = open('files/data/HadSEEP_monthly_qc.txt','r') sdata = fp.readlines() fp.close() labels = sdata[3].split() data = [i.split() for i in sdata[4:]] j = 0 rdata = [[float(data[i][j]) \ for i in xrange(len(data))]\ for j in xrange(len(data[0]))] print rdata[0] # set up a dataset = {} for i,k in enumerate(labels): dataset[k] = rdata[i] print dataset['YEAR'] dataset = dict(zip(labels,rdata)) print dataset['YEAR'] import pylab as plt %pylab inline for i,JFM in enumerate([['JAN','FEB','MAR'],['APR','MAY','JUN'],\ ['JUL','AUG','SEP'],['OCT','NOV','DEC']]): plt.figure(i,figsize=(14, 6)) plt.xlabel('Year') plt.ylabel('Precip. (mm)') for month in JFM: plt.ylim(0,250) plt.xlim(dataset['YEAR'][0],dataset['YEAR'][-1]) plt.title(str(JFM)) plt.plot(dataset['YEAR'],dataset[month]) plt.figure(i+1,figsize=(14, 6)) plt.xlabel('Year') plt.ylabel('Precip. (mm)') plt.title('ANN') plt.ylim(0,1100) plt.xlim(dataset['YEAR'][0],dataset['YEAR'][-1]) plt.plot(dataset['YEAR'],dataset['ANN']) # Read files/data/heathrowdata.txt as above into data as float # doing some clever things to deal with file markers # i.e. where it says # Provisional or # we will not worry about # that for the moment # where it has fillers, ---, replace by -999 fp = open('files/data/heathrowdata.txt','r') ldata = [i.replace('---','-999').replace('# Provisional','').replace('#','').split() \ for i in fp.readlines()[7:]] data = [[float(k) for k in j] for j in ldata] fp.close() # The reading by line is a bit inconvenient, so rotate the # dataset rdata = [[data[j][i] for j in xrange(len(data))] for i in xrange(len(data[0]))] # set some labels for each column labels = ['year','month','tmax (degC)','tmin (degC)',\ 'air frost (days)','rain (mm)','sun (hours)'] # generate a dictionary with the labels as keys items = dict(zip(labels,rdata)) import pylab as plt # its quite difficult to add arrays # so we have to loop over each item time = [items['year'][i] + items['month'][i]/12. for i in xrange(len(items['year']))] for i,label in enumerate(labels[2:]): plt.figure(i,figsize=(14, 6)) plt.xlabel('year') plt.ylabel(label) # filter out the -999 values x = [time[j] for j,i in enumerate(items[label]) if i != -999] y = [i for i in items[label] if i != -999] plt.plot(x,y) data = "1964 1220 1974 2470 1984 2706 1994 4812 2004 2707" sdata = data.split() for i in xrange(0,len(sdata),2): print ' '.join(sdata[i:i+2]) fdata = [int(s) for s in data.split()] print fdata data = "1964 1220 1974 2470 1984 2706 1994 4812 2004 2707" fdata = [] for s in data.split(): fdata.append(int(s)) print fdata data = "1964 1220 1974 2470 1984 2706 1994 4812 2004 2707" fdata = [int(s) for s in data.split()] # use slicing to separate the odd # and even data years = fdata[0::2] emissions = fdata[1::2] print years print emissions fdata = (int(s) for s in data.split()) print 'fdata is',fdata for i in fdata: print i