Python
-
print 1 / 3, 5 / 2, -7 / 3 # print out float numbers with at most 15 digits; print 1 // 3, 5 // 2, -7 // 3 # print out integers => 0 , 2, -2;
print "Let's talk about %s" % my_name # format print, variable my_name = 'Wade';
print "." * 10 # print out 10 .s
fat_cat = """ # documentation comments """
I'll do a list:
\t* cat food
\t* Fishes
\t* Catnip\n\t* Grass
""" # you also can use '''
from sys import argv
script, first, second, third = argv
a = 'Hello'
a[1:3] >>> 'el'
my_string[::-1] # reverse a string
for string and list, these are common builtin function:
1.a = [1, 2, 3] a.append(5); del a; a.pop(2); 2 in a; for num in a: ...
a = [4, 2, 1, 5]
sorted(a) >>>[1, 2, 4, 5]
b = ':'.join(a) >>> string func not working here
b.split(':') >>>
range(3) >>> [0, 1, 2] - Ctrl-D to get out of python in the terminal.
- put these characters in the first line to use UTF-8 coding: #--coding: utf-8--
- a little debugging technique: checking code from back to front word by word.
- function round(): round(1.733) #=> 2.0
- %s using str() to do convertion, and %r using repr(); %r is used for debugging, since it displays the "raw" data of the variable.
- if else elif; raw_input('-->')
- If you have somethin to ask, just type: pydoc raw_input; q to quit
- in python interpretor, you can use dir() or help() function to get help.
- string, tuple is fixed, and list can shrink and grow.
- (x, y) = (1, 2) #parallel assignment
- A Python module can be run directly or it can be imported and used by some other module. When a Python file is run directly, the special variable "__name__" is set to "__main__". Therefore, it's common to have the boilerplate
if __name__ ==...
shown above to call a main() function when the module is run directly, but not when the module is imported by some other module. - open(name[, mode[, buffer]]): mode: "r": reading, "w" writing, "a": appending; from_file.close()
- let f be a file, f.seek(0) : moving to the start of the file. Each time you do f.readline() you're reading a line from the file, and moving the read head to right after the \n that ends that file.
- when you do import, you do not need to put the .py at the end to import it. you have file ex07.py, you should do: import ex07. In terminal, you type pydoc somemodule.somefunction, then it will come up some documents describing it.
- pop(0), pop(-1)
- exit(0): exit program
- every if-statement must have an else, if not you have to use a die function and print out a error message. nest if less than 2 times! or put it in another function.
- never use while loop unless you want to loop forever. Use print to debug. Code a little, run a little, fix a little.
-
foo = ['a', 'b', 'c', 'd', 'e'] from random import choice print choice(foo)
- collections.OrderedDict: http://pymotw.com/2/collections/ordereddict.html collections.OrderedDict remembers the order when things added.
- pass, break, continue: http://www.tutorialspoint.com/python/python_loop_control.htm
- thing = MyClass() # instantiate a class
.strip()
removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.- list.count(obj) # return times obj occurs in list.
-
shuffleMe = [0,1,2,3,4,5,6,7,8,9] random.shuffle(shuffleMe) print(shuffleMe) //[2, 4, 6, 3, 7, 8, 0, 5, 9, 1]
pickChars ="some things to pick"
print random.sample(pickChars,6) //['c', 's', 'e', 'n', 'g', ' '] pickNums =[0,1,2,3,4,5,6,7,8,9]
print random.sample(pickNums,5) //[6, 4, 5, 9, 8]>>> phrase ='lexical semantics'
>>> phrase.capitalize() //'Lexical semantics'
>>> phrase.upper() //'LEXICAL SEMANTICS'
>>> phrase.title() //'Lexical Semantics'
b = 'This is a string'
b[k] = b[-len(b) + k]
a = '0123456789'
c = a[start:stop:step]
a[2:6] = a[2:6:1] = '2345'
a[:] = a[0:len(a):1]
a[::2] = '02468'
a[6:2:-1] = '6543'
a[::-1] = a[-1::-1] #reverse a string - list2 = list1[:] # copying lists using slice
- The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. str.replace(old, new[, max])
-
a,b,_ = 0,1,2 -> dismisses the 2 a,_,c = 0,1,2 -> dismisses the 1 _,_,c = 0,1,2 -> dismisses the 0 and 1 a,b = 0,1,2 -> ERROR: too many values to unpack t = 0,1,2 -> creates the tuple t=(0,1,2), 'packing' the values v, w, x = t -> sets v=0, w=1 and x=2, 'unpacking' the values v, w = t -> ERROR: need more than 2 values to unpack
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)[5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)):
print i, a[i] - Most of the uses of inheritance can be simplified or replaced with composition, and multiple-inheritance should be avoided at all costs.
- parent and child interact in 3 ways: 1. imply(call parent method); 2. override; 3. overload.
- When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!
- using \x, \u or \U escapes is the preferred way to include non-ASCII data in string literals.
- exit(0): successful exit; exit(1):there was some issue / error / problem and that is why the program is exiting.
-
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- "\" or "()" to continue multiple lines:
1 >>> b = ((i1 < 20) and 2 ... (i2 < 30) and 3 ... (i3 < 40)) 4 >>> b 5 True 6 >>> 7 >>> b = (i1 < 20) and \ 8 ... (i2 < 30) and \ 9 ... (i3 < 40) 10 >>> 11 >>> b 12 True
-
1 from datetime import datetime 2 now = datetime.now() 3 print now # 2013-04-16 20:38:35.308367
# now.day now.year now.month represents day year month
# some_string.isalpha() return True or False to test if the variable contains only characters -
1 # splat arguments: 2 def favorite_actors(*args): 3 """Prints out your favorite actorS (plural!)""" 4 print "Your favorite actors are:" , args
# Splat arguments are an arbitrary number of arguments, and you use them by preceding your parameter with a*
. -
1 from module import function # function import : from math import sqrt; sqrt(); 2 import module # generic import : math.sqrt()
3 from math import * # import all thins in math; not recommended - Built in function:
- max(): takes any number of arguments and returns the largest one.
- min(): opposite of max();
- abs(): returns the absolute value of the number it takes as an argument
- type(): it returns the type of the data it receives as an argument.
- Dictionary:
- d = ['key1':1, 'key2':2, 'key3':3]
- d['key2'] = 5
- d[new_key] = new_value # add new pair
- del d[key_name] # remove item based on key_name
- d.remove(value) # will remove the the first item from d that has a value equal to value
-
1 #!/usr/bin/python 2 3 aList = [123, 'xyz', 'zara', 'abc', 'xyz']; 4 5 aList.remove('xyz'); // remove the firs occurrence of a value from a list. 6 print "List : ", aList; 7 aList.remove('abc'); 8 print "List : ", aList;
n = [1, 3, 5] n.pop(1) // .pop() method returns the last element, and remove it from the list. # Returns 3 (the item at index 1) print n # prints [1, 5]
range(arg1,[arg2, [arg3]]):
one arg:
range(1) => [0]; range(2) => [0, 1]
two arg:
range(1, 3) => [1, 2]
three arg:
range(2, 8, 3) #=> [2, 5]; range(2, 9, 3) #=> [2, 5, 8] -
1 li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret'] 2 s = ";".join(li) 3 # s => 'server=mpilgrim;uid=sa;database=master;pwd=secret' 4 s.split(";") 5 # ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret'] 6 s.split(";", 1) 7 # ['server=mpilgrim', 'uid=sa;database=master;pwd=secret']
- random.randint(start,stop): return start less or equal than N, N bigger or equal than stop.
- raw_input(">>>"): returns a string of user input
while
/else
is similar toif
/else
, but there is a difference: theelse
block will execute anytime the loop condition is evaluated toFalse
. This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of abreak
, theelse
will not be executed.- A new built-in function, enumerate(), will make certain loops a bit clearer.
enumerate(thing)
, where thing is either an iterator or a sequence, returns a iterator that will return a tuple(0, thing[0])
,(1, thing[1])
,(2, thing[2])
, and so forth. - [pair for pari in enumerate(mylist)]
1 x = [1, 5, 7, 3, 8] 2 print("x = "+str(x)) 3 for ind, itm in enumerate(x): 4 print("x["+str(ind)+"] = "+str(itm)) 5 '''The ouput of this snippet is: 6 x = [1, 5, 7, 3, 8] 7 x[0] = 1 8 x[1] = 5 9 x[2] = 7 10 x[3] = 3 11 x[4] = 8'''
-
1 alist = ['a1', 'a2', 'a3'] 2 blist = ['b1', 'b2', 'b3'] 3 4 for a, b in zip(alist, blist): 5 print a, b 6 7 alist = ['a1', 'a2', 'a3'] 8 blist = ['b1', 'b2', 'b3'] 9 10 for i, (a, b) in enumerate(zip(alist, blist)): 11 print i, a, b
Results:
0 a1 b1 1 a2 b2 2 a3 b3 - for/else: else statement is executed after the for, but only if the for ends normally—that is, not with a break
- the Python function
items()
will iterate over a dictionary and return those key/value pairs.items()
returns an array of tuples* with each tuple consisting of a key/value pair from the dictionary Note that theitems()
function doesn't return key/value pairs in any specific order.1 d = { 2 "Name": "Guido", 3 "Age": 56, 4 "BDFL": True 5 } 6 d.items() // d.clear() #=> d = {} 7 # => [('BDFL', True), ('Age', 56), ('Name', 'Guido')]
- The
keys()
function returns an array of the dictionary's keys, and; Thevalues()
function returns an array of the dictionary's values. - list comprehensions:
doubles_by_3 = [x*2 for x in range(1,6) if (x*2)%3 == 0] # => [6]
- list slicing: [start: end: stride]
- lambda construct: (anonymous function) you can put a lambda definition anywhere a function is expected. if we need it only once and it's quite simple
1 >>> def f (x): return x**2 2 ... 3 >>> print f(8) 4 64 5 >>> 6 >>> g = lambda x: x**2 7 >>> 8 >>> print g(8) 9 64
10 foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
11 print filter(lambda x: x % 3 == 0, foo) # [18, 9, 24, 12, 27]
12 print reduce(lambda x, y: x + y, foo) # sum: 139
13 print map(lambda x: x * 2 + 10, foo) #[14, 46, 28, 54, 44, 58, 26, 34, 64]
# lambda syntax:lambda variable: expression
- filter():
filter()
calls our lambda function for each element of the list, and returns a new list that contains only those elements for which the function returned "True". - bin() function:
bin
takes an integer as input and returns the binary representation of that integer in a string. You can also represent numbers in base 8 and base 16 using theoct()
andhex()
functions. - class: variables that are available everywhere (global variable); variables that are only available to members of a certain class (member variables); variables that are only available to particular instances of a class (instance variables)
- overide:
1 class DerivedClass(Base): 2 def some_method(self): 3 super(DerivedClass, self).meth() 4 # meth() is a method of superclass 调父类方法
- member variable should be accessed by self.var1;
- __repr__():
- IO: my_file = open("output.txt", "r+") # r+: read and write; w: only write; r: only read; a: append new data; file.readline()
- file objects contain a special pair of built-in methods:
__enter__()
and__exit__()
. The details aren't important, but what isimportant is that when a file object's__exit__()
method is invoked, it automatically closes the file. How do we invoke this method? Withwith
andas:
1 with open("text.txt", "w") as textfile: 2 textfile.write("Success!")
- Python file objects have a
closed
attribute which isTrue
when the file is closed andFalse
otherwise. - function: python function will return a value or None instead if no return statement.
- Everything between the triple quotes is the function's doc string, which documents what the function does. doc string, if exists, must be the first thing defined in a function. Function is an object, and it has attributes.
1 # example code: in module(d01.py) 2 def ex(params): 3 ''' blablabla ''' 4 5 /// console: 6 >>>import d01 7 >>>print ex.__doc__ #=> blablabla
- once you import a module, you can reference any of its public functions classes or attributes. You can access its function with module.function
- Python looks in several places if you try to import a module. Specifically, it looks in all the directories defined in sys.path(this just is a list)
1 >>> import sys 2 >>> sys.path 3 [blabla...] 4 >>>sys 5 <module 'sys' (built-in)> // the sys module is written in C 6 >>>sys.path.append('/my/new/path') // sys.path is a list of directories names that constitute the current search path
- Everything is an object. Meaning that it can be assigned to a variable or passed as an argument to a function.
- Modules are objects, and all modules have a built-in attribute __name__, If you import the module, then __name__ is the module's filename, without a directory path or file extension. But you can also run the module directly as a standalone program, in which case __name__ will be a special default value, __main__.
- Lists:
1 >>> li 2 ['a', 'b', 'mpilgrim', 'z', 'example'] 3 >>> li.append("new")
3 >>> li.index('mpilgrim') #=> 3 .index('value') method returns the first occurrence of a value's index.
3 >>> 'c' in li #=> False use in to test weather an item is in the list 4 >>> li 5 ['a', 'b', 'mpilgrim', 'z', 'example', 'new'] 6 >>> li.insert(2, "new") 7 >>> li 8 ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new'] 9 >>> li.extend(["two", "elements"]) # concatenates two lists. 10 >>> li 11 ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
12 >>> li = ['a','b','mpilgrim']
13 >>> li = li + ['c','d']
14 ['a','b','mpilgrim','c','d']
15 //+ returns a new concatenated list but .extend() method alters the original list(faster); li += ['c','d'] works as extend.
16 >>> li = [1, 2] * 3
17 [1, 2, 1, 2, 1, 2] // * repeater.
18 // tuple: t = ("a", "b", "mpilgrim", "z", "example")
19 // tuple has no method, but can do this: 'z' in t >>> True
20 // why use tuple:1. faster than list(循环最好用tuple); 2.tuples can be used as dictionary keys(list can't, dictionary keys must be immutable) - n
- n
- n
- n
- n
- n
- n
- n
- n