[python] 20131112

#demo program

1
2
3
4
5
6
a,b=0,1     # 指定值至變數中
while b<10: # 迴圈
... print(b, end=',') # 顯示文字,結尾加上,
... a,b=b,a+b # 指定值至變數中

1,1,2,3,5,8, # 輸出結果

#Control Flow Tools

if

1
2
3
4
5
6
if x<0:
something something
elif condition:
something something
else:
something something

for

1
2
3
4
5
6
7
words=['cat','window','defenestrate']
for w in words:
print(w,len(w))

cat 3
window 6
defenestrate 12
1
2
3
4
5
6
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w) # 將值插入至list中
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

range()

range()主要的目的是要創造一個連續值的list, 例如 range(10)=[0,1,2,3,4,5,6,8,9]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
>>> for i in range(5): # range(5) = range(0,5)
... print(i)
...
0
1
2
3
4

>>> for i in range(5,9):
... print(i)
...
5
6
7
8

>>> for i in range(0,10,2): # = for(i=0;i<10;i=i+2) step 2
... print(i)
...
0
2
4
6
8

# 使用在文字陣列上
>>> 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

break, continue, else in Loops

1
2
3
4
5
6
7
for n in range(2,10):
for x in range(2,n):
if n%x ==0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')

else: 是對應到 for x in range(2,n): 意義: a try statement’s else clause runs when no exception occurs

#python coding style

  1. Use 4-space indentation, and no tabs.

    4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.

  2. Wrap lines so that they don’t exceed 79 characters.

    This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

  3. Use blank lines to separate functions and classes, and larger blocks of code inside functions.

  4. When possible, put comments on a line of their own.

  5. Use docstrings. 「」" something something something 「」" 可以被呼叫by function.doc

  6. Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).

  7. Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).

  8. Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.

  9. Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.