在http://docs.python.org/ 中学习Python ,下面写一些自己的笔记
【1】发现一个奇怪的事情,自己写的代码总是报错,而复制上面的代码却正常!
解决:原来是不能将空格和Tab混用,在Python中,严格要求缩进,一个缩进就是一个块
【2】Python中使用j 或J作为复数的虚部符号。如
>>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5 【3】字符串String记得加‘’
>>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.'
>>> word[:2] # The first two characters 'He' >>> word[2:] # Everything except the first two characters 'lpA' 【4】不能直接修改数组中的元素,但是可以将原数组部分与修改的值相加起来【5】不同C/C++中的if语句,这里的if后要加冒号>>> word[0] = 'x' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment >>> 'x' + word[1:] 'xelpA' >>> 'Splat' + word[4] 'SplatA'
>>> x = int(raw_input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More' ... More
【6】for循环
>>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print w, len(w) ... cat 3 window 6 defenestrate 12 >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] #若修改了数组元素的话,数组名后要加[:]使用range循环>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb
这个例子比较奇怪:>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3else 语句属于for,并不是if,当没有执行break,才执行else
【7】pass可以作为注释,当你没相到的时候,可以用pass在哪里注释
【8】过滤器:【9】>>> def f(x): return x % 2 != 0 and x % 3 != 0 ... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23]
>>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #等价于下面: >>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #也可用zip()转置 >>> zip(*matrix) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]