TypeError
exception
The following examples are compatible with Python 2.7
python
in the shell
$ python Python 2.7.8 (default, Aug 24 2014, 21:26:19) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
>>> a = 2 # <type 'int'> >>> b = 3.0 # <type 'float'> >>> a / b 0.6666666666666666 >>> 2/3 # 0.6666666666666666 in Python 3 0 >>> a**100 # a to the power of 100 1267650600228229401496703205376L >>> help('int') Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer ...
>>> c = "abcde" # same as single quote 'abcde' >>> len(c) 5 >>> c[1] # Python use 0-based indexing 'b' >>> c[1:3] 'bc' >>> print 'integer: {}, float: {}'.format(3, 5.12) integer: 3, float: 5.120000 >>> '3' + 5 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
>>> d = [a, b, c] >>> d [2, 3.0, 'abcde'] >>> d[0] 2 >>> d[1:] + [['foo', 'bar'], 123] [3.0, 'abcde', ['foo', 'bar'], 123] >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> "1 2 3 4 5".split() ['1', '2', '3', '4', '5']
>>> x = [0, 1, 2, 3] >>> y = x >>> y[0] = 'ha' >>> x ['ha', 1, 2, 3]
def f(n): ..for x in range(n): ....if x % 2 == 0: ......print x, 'is even.' ....else: ......print x, 'is odd.' ..else: # Run if the for loop is not break ......print 'ok' ..return ('a', 'b', 'c') # Return a tuple
>>> x = f(4) 0 is even. 1 is odd. 2 is even. 3 is odd. ok >>> x ('a', 'b', 'c') >>> a, b, c = x # Tuple unpacking >>> a 'a'
>>> e = {'Alice': 9372, 'Bob': 138, 'Carol': 7347} >>> for (key, val) in e.items(): ... print key, ' ->', val ... Bob -> 138 Alice -> 9372 Carol -> 7347
>>> x = [] >>> for i in range(10): ... x.append(i**2) >>> x [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [i**2 for i in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> map(lambda i: i**2, range(10)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
True
not False
[1, 2, 3] and True
False or {"Bob": 138}
False
None
0
[]
, {}
, ()
, etc.
module_name.py
, use import module_name
>>> import random >>> random.randint(1, 100) # Range from [1, 100] 43 >>> import itertools >>> list(itertools.combinations('abcd', 3)) [('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]
if __name__ == '__main__': # Do something when this file is executed as a program.
def qsort(lst): """This implements quick sort.""" if lst == []: return [] pivot = lst[0] smaller = qsort([x for x in lst[1:] if x < pivot]) bigger = qsort([x for x in lst[1:] if x >= pivot]) return smaller + [pivot] + bigger
def plus3(n): return n+3 def times2(n): return n*2 >>> plus3(4) Calling plus3 7 >>> times2(3) Calling times2 6
@Log def plus3(n): return n+3 def plus3(n): return n+3 plus3 = Log(plus3)
def Log(func): def logged_func(*args, **kwargs): print "Calling", func.__name__ return func(*args, **kwargs) return logged_func class Log(object): def __init__(self, func): self.f = func def __call__(self, *args, **kwargs): print 'Calling', self.f.__name__ return self.f(*args, **kwargs)
os
, re
, sqlite3
, json
, etc.
import this
in the Python interpreter?>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. ... [skip 12 lines]
python -m pdb some_prog.py
import pdb; pdb.set_trace()
import ipdb; ipdb.set_trace()
class Duck: def speak(self): print 'Quack!' class Cat: def speak(self): print 'Meow!' def happy(x): x.speak() >>> d = Duck() >>> c = Cat() >>> happy(d) Quack! >>> happy(c) Meow!
class C(object): def f(self): print 'f()' >>> c = C() >>> dir(c) ['__class__', '__delattr__', '__dict__', '__doc__', ..., 'f'] >>> c.val = 123 >>> dir(c) ['__class__', '__delattr__', '__dict__', '__doc__', ..., 'f', 'val'] >>> c.g() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'C' object has no attribute 'g' >>> def g(): print 'g()' >>> c.g = g >>> c.g() g()