Useful py stuff I keep forgetting…
Get the time elapsed since a process started:
begin = datetime.datetime.now()
# do some stuff…
duration=datetime.datetime.now() – begin
print(“finished after “+str(duration.seconds)+” seconds”)
Working with strings
- if ‘dog’ in ‘hotdog’ # returns True
- “hot$dog”.split(“$”) # returns the sequence ['hot','dog']
Formatting
- “value %i” % myValue
Formats myValue as an integer - “value “+str(5)
Convert 5 to a string and concatenate it with “value “
Arrays (aka python sequences)
- nOObs=[] # create an empty array
- len(array) # returns the number of elements
- array.append(elem) # add an element
Math
- fabs(x) in math (absolute value)
- floor(x), ceil(x)
- division by zero yields an error unlike C/C++
Iterators
- for x in arr # if arr is an array/sequence
- for x in range(N) # iterate in the range [0,N[
- for x in range(1,N) # iterate in the range [1,N[
Importing modules
- from math import fabs
=> import only the fabs function - from math import *
=> import everything from the math module - import math
=> import the math module (still needs math.fabs(x) instead of fabs(x) )
Truths and Falsehoods
- True # gets an uppercase
- False # gets an uppercase
- if(None) # that is False
- if(None==False) # that is also False
- true, false, yes, no, Yes, No are undefined
Caveats
- if(x==y) return 0 # WRONG
=> if(x==y) : return 0 #OK - if(!x) # WRONG
=> if not x - (x||y) # WRONG
=> x or y - (x && y) # WRONG
=> x and y - def myFunction() # MISSING COLON AT END
=> def myFunction(): - “value: “+5 # WRONG
=> “value: ” + str(5)
Links
- A verbose but informative article about python introspection (ibm.com)


Comments