Sunday, March 27, 2016

Python Braindump

from math import * import random #Python 3.4.1/IDLE
while int(num)>10:  # : is code block
    print("too big") # clean code by indentation
    num=input()
# code block end by indentation, not space
message="see {0} and {1}" print(message.format(1,random.randint(1,100)))
def load_data(): return "1" load_data() #important (): ()
if: elseif: else: for c in w: while True: break try: except: finally:
list c=["Red",'red',"Blue"] c.sort() reverse() append("R") count("R") len(c)
w="_"*6 for c in w: print(c," ",end="") str_as_list=list("cheese"),lst=[]
for i in range(1,100): "K" in "Kol"  "this".[:1] is t .[2:]
tuple vs list () vs [] --multi type c=[1,'cat'] t= 1, "cat" t=(1,"cat")
append,c[0]=2 vs. readonly unpacking i,str=t def get_t(): return i, str
[] help () -- c,i=get_cmd_item_tuple() c=line[:1] i=line[2:] return i,c
if c=="d" and i in c.remove(i)  # tuple faster, list more functionality
[],(),{},{:} --list,tuple,set()=unordered list no index, no append but add
dict() key index d[k]=v no add/append, list append not add. d={} is dict not set
s1^s2 s1&s2 s1-s2 s1|s2  len() in works for []/()/{}/{:} in key not val.
del lst[0] del d[0] s={1,2,3,"str"} s.pop() is remove s.remove("str")
class Person: def run(self): p=Person() p.run() def __init__(self,n=""):
self.dynamic_name=n  p.dynamic_name="allen" >>p1 mem hex id(p1) int p1 is p2
self._p is private naming convention only raw representation=toString() type(c)
def __repr__(self):return "{0} {1}".format(Person,self.__dict__) __dict__ prop
file structure --- main.py \package1\module1.py must have __init__.py init pkg
import package1  p=package1.module1.Person() # avoid long name???
>>__name__ shows '__main__' print(__name__) shows '__package1.module1__'
from hr import person p=person.Person() # * could be bad practice
from pkg import (m1,m2) from  urllib.request import urlopen #symbol=def
from  urllib.request import urlopen # one way to avoid long name
with urlopen("http://www.cnn.com") as story: #symbol used without pkg.mod
    for line in story:
        print(line.decode('utf8'))

def main(): """docstring seen in help def and module level"""
if __name__=="__main__": main() #module used as main.py so define entry point
sys.argv[0] is main.py argv[1] is 1st param #!/usr/bin/env python3 #Shabang
__file__ sys.argv=[sys.argv[0],0] IDLE command line except (ValueError, TypeE):
try: import msvcrt def f(): except: print("import err") alt-3/4 comment
except (ValueErr,ArithmeticError) as e: print(e) print(str(e))
raise pass print("{}".format(str(e)), file=stderr) raise ValueError()
p=os.getcwd() os.chdir(p) os.mkdir("test")

r=@ in C# r"c:\working\bash"  list("test it")=>[t,e,s,t,' ',i,t] 
str(b'\345')=>b'\\xes" '\345' is UTF-8
network pass along b'data' need .encode/.decode('utf-8')
value vs id=ptr == vs is p==q T same content p is q F bcoz id(p)!=id(q)
optional param eval only once def f(m=[]) m.append('a')=>'aaa' on f(),f()
f(c=ctime) same problem so m=None instead.
LEGB rule --- gc=0 def set() gc=3 not change gc since it is local scope.
 def set2() global gc gc=3 will change gc
Help system --- import words dir(words)=>'__fetch_words',... dir(itertools)
everything is object including module and symbols
t=(39) is int t=(39,) is tuple, unpacking (a,(b,c))=(1,(2,3))
p=1,2,3 type(p) shows tuple not []
join vs split ---';'.join(['a','b','c']).split(';')
"x of y of z".partition('of')=>('x','of','y of z') only split by 1st


No comments:

Post a Comment