# Jean-Baptiste Juin # Astronomy Python course # Practice 1 #------------------------ #------------------------ # Title: ipython basics #------------------------ #------------------------ #------------------------ # Calculator #------------------------ # Float/Int distinction 3/2 3./2. # Recall preceding result _*2. #------------------------ # Strings manipulation #------------------------ s1='Hello' s2='world' s=s1+" "+s2 print s print (s1+'-'+s2+' ')*3 # Accessing string s[0] s[-1] # Slicing s[0:5] # String are objects: some methods s.title() s.lower() s.upper() ls=s.split() # Counting elements s.count('o') print ls #------------------------ # Lists (and tuples) #------------------------ ls[0] ls[1] print ls # length of a list len(ls) # adding an element to a list ls.append(5.0) ls.append(5.0) print ls len(ls) # counting elements ls.count(5.0) # removing element ls.remove('world') # inserting element ls.insert(1,'world') # loop in a list for element in ls: print element # Declare a new list: ls2=['Hola','Mundo',57,-2.5] # Concatenation of lists ls3=ls+ls2 # list of lists lsc=[ls,ls2,[3.1,4.2,-5.3]] #------------------------ # Dictionnaries #------------------------ # Declaring a dictionnary d={} # Adding elements d['Name']='ABELL3667' d['RA']=[20,26,21.4] d['DEC']=[-56,48,60.0] d['LX']=[9.15] print d # Iterating in elements for k in d.keys(): print k,d[k] # Getting the list of the values or keys d.keys() d.values() #------------------------ # ASCII i/o #------------------------ # Output f=open("./output.txt",'w') for k in d.keys() f.write(k+": "+str(d[k])+"\n") f.close() # Input f=open("./Practice1.txt",'r') Values=[] for line in f: l=line.split() for i in xrange(len(l)): l[i]=float(l[i]) Values.append(l) f.close() print Values #------------------------ # Pickle #------------------------ # Pickle ~ equivalent a save/load de IDL # Pickle module esta en ipython si no: #import pickle # Writing f=open("./test.pickle","w") pickle.dump(Values,f) f.close # Reading f=open("./test.pickle","r") Result=pickle.load(f) f.close() print Result #------------------------ # Date/Time #------------------------ import time print time.localtime() print time.ctime() import datetime hoy=datetime.date(2007,8,14) man=datetime.date(2007,9,15) delay=hoy-man print delay delay delay2=datetime.timedelta(18) print hoy+delay2 hoy.weekday() hoy.month #------------------------ # iPython Magic functions #------------------------ %hist # To save some commands %save "./commands.txt" 10 12-15 # To log input-output %logstart -t -o %logoff # To know defined variables %who %whos