1.. _python-basics: 2 3Basic Python Constructs 4======================= 5 6Basic Python data types (``int``, ``float``, ``str``, ``tuple``, 7``list``, ``array``, ``dict``, ``obj``) and programming constructs 8(``if`` statements, ``for`` loops, functions w/ keyword arguments) are 9briefly overviewed below. All examples can be executed interactively in 10Python. To do this, type “``python``” at the command line and paste any 11of the shaded text below at the “``>>>``” prompt. For more information 12about effective use of Python, consult the detailed online 13documentation: https://docs.python.org/2/. 14 15Intrinsic types: ``int, float, str`` 16------------------------------------ 17 18.. code:: rest 19 20 #this is a comment 21 i=5 # integer 22 f=3.6 # float 23 s='quantum/monte/carlo' # string 24 n=None # represents "nothing" 25 26 f+=1.4 # add-assign (-,*,/ also): 5.0 27 2**3 # raise to a power: 8 28 str(i) # int to string: '5' 29 s+'/simulations' # joining strings: 'quantum/monte/carlo/simulations' 30 'i={0}'.format(i) # format string: 'i=5' 31 32Container types: ``tuple, list, array, dict, obj`` 33-------------------------------------------------- 34 35.. code:: rest 36 37 from numpy import array # get array from numpy module 38 from generic import obj # get obj from generic module 39 40 t=('A',42,56,123.0) # tuple 41 42 l=['B',3.14,196] # list 43 44 a=array([1,2,3]) # array 45 46 d={'a':5,'b':6} # dict 47 48 o=obj(a=5,b=6) # obj 49 50 # printing 51 print t # ('A', 42, 56, 123.0) 52 print l # ['B', 3.1400000000000001, 196] 53 print a # [1 2 3] 54 print d # {'a': 5, 'b': 6} 55 print o # a = 5 56 # b = 6 57 58 len(t),len(l),len(a),len(d),len(o) #number of elements: (4, 3, 3, 2, 2) 59 60 t[0],l[0],a[0],d['a'],o.a #element access: ('A', 'B', 1, 5, 5) 61 62 s = array([0,1,2,3,4]) # slices: works for tuple, list, array 63 s[:] # array([0, 1, 2, 3, 4]) 64 s[2:] # array([2, 3, 4]) 65 s[:2] # array([0, 1]) 66 s[1:4] # array([1, 2, 3]) 67 s[0:5:2] # array([0, 2, 4]) 68 69 # list operations 70 l2 = list(l) # make independent copy 71 l.append(4) # add new element: ['B', 3.14, 196, 4] 72 l+[5,6,7] # addition: ['B', 3.14, 196, 4, 5, 6, 7] 73 3*[0,1] # multiplication: [0, 1, 0, 1, 0, 1] 74 75 b=array([5,6,7]) # array operations 76 a2 = a.copy() # make independent copy 77 a+b # addition: array([ 6, 8, 10]) 78 a+3 # addition: array([ 4, 5, 6]) 79 a*b # multiplication: array([ 5, 12, 21]) 80 3*a # multiplication: array([3, 6, 9]) 81 82 # dict/obj operations 83 d2 = d.copy() # make independent copy 84 d['c'] = 7 # add/assign element 85 d.keys() # get element names: ['a', 'c', 'b'] 86 d.values() # get element values: [5, 7, 6] 87 88 # obj-specific operations 89 o.c = 7 # add/assign element 90 o.set(c=7,d=8) # add/assign multiple elements 91 92An important feature of Python to be aware of is that assignment is most 93often by reference, *i.e.* new values are not always created. This point 94is illustrated below with an ``obj`` instance, but it also holds for 95``list``, ``array``, ``dict``, and others. 96 97.. code:: rest 98 99 >>> o = obj(a=5,b=6) 100 >>> 101 >>> p=o 102 >>> 103 >>> p.a=7 104 >>> 105 >>> print o 106 a = 7 107 b = 6 108 109 >>> q=o.copy() 110 >>> 111 >>> q.a=9 112 >>> 113 >>> print o 114 a = 7 115 b = 6 116 117Here ``p`` is just another name for ``o``, while ``q`` is a fully 118independent copy of it. 119 120Conditional Statements: ``if/elif/else`` 121---------------------------------------- 122 123.. code:: rest 124 125 a = 5 126 if a is None: 127 print 'a is None' 128 elif a==4: 129 print 'a is 4' 130 elif a<=6 and a>2: 131 print 'a is in the range (2,6]' 132 elif a<-1 or a>26: 133 print 'a is not in the range [-1,26]' 134 elif a!=10: 135 print 'a is not 10' 136 else: 137 print 'a is 10' 138 #end if 139 140The “``#end if``” is not part of Python syntax, but you will see text 141like this throughout the Project Suite for clear encapsulation. 142 143Iteration: ``for`` 144------------------ 145 146.. code:: rest 147 148 from generic import obj 149 150 l = [1,2,3] 151 m = [4,5,6] 152 s = 0 153 for i in range(len(l)): # loop over list indices 154 s += l[i] + m[i] 155 #end for 156 157 print s # s is 21 158 159 s = 0 160 for v in l: # loop over list elements 161 s += v 162 #end for 163 164 print s # s is 6 165 166 o = obj(a=5,b=6) 167 s = 0 168 for v in o: # loop over obj elements 169 s += v 170 #end for 171 172 print s # s is 11 173 174 d = {'a':5,'b':4} 175 for n,v in o.items():# loop over name/value pairs in obj 176 d[n] += v 177 #end for 178 179 print d # d is {'a': 10, 'b': 10} 180 181Functions: ``def``, argument syntax 182----------------------------------- 183 184.. code:: rest 185 186 def f(a,b,c=5): # basic function, c has a default value 187 print a,b,c 188 #end def f 189 190 f(1,b=2) # prints: 1 2 5 191 192 193 def f(*args,**kwargs): # general function, returns nothing 194 print args # args: tuple of positional arguments 195 print kwargs # kwargs: dict of keyword arguments 196 #end def f 197 198 f('s',(1,2),a=3,b='t') # 2 pos., 2 kw. args, prints: 199 # ('s', (1, 2)) 200 # {'a': 3, 'b': 't'} 201 202 l = [0,1,2] 203 f(*l,a=6) # pos. args from list, 1 kw. arg, prints: 204 # (0, 1, 2) 205 # {'a': 6} 206 o = obj(a=5,b=6) 207 f(*l,**o) # pos./kw. args from list/obj, prints: 208 # (0, 1, 2) 209 # {'a': 5, 'b': 6} 210 211 f( # indented kw. args, prints 212 blocks = 200, # () 213 steps = 10, # {'steps': 10, 'blocks': 200, 'timestep': 0.01} 214 timestep = 0.01 215 ) 216 217 o = obj( # obj w/ indented kw. args 218 blocks = 100, 219 steps = 5, 220 timestep = 0.02 221 ) 222 223 f(**o) # kw. args from obj, prints: 224 # () 225 # {'timestep': 0.02, 'blocks': 100, 'steps': 5} 226