1.自定義分隔符:
>>> print("I", "wish", "to", "register", "a", "complaint", sep="_",end='') seq 默認爲‘ ’end='\n'
I_wish_to_register_a_complaint express
2.用做布爾表達式(如用做if語句中的條件)時,下面的值都將被解釋器視爲假:app
False , None , 0, " ", ( ) ,[ ] ,{ } 換而言之,標準值False和None、各類類型(包括浮點數、複數等)的數值0、空序列(如空字符串、空元組和空列表)以及空映射(如空字典)都被視爲假,而其餘各類值都被視爲真,包括特殊值True。函數
3.條件表達式:ui
status = "friend" if name.endswith("Gumby") else "stranger" this
若是爲真 ,提供的第一個值'friend',不然則爲假 ,提供後面一個值'stranger'spa
4.短路邏輯和條件表達式orm
name = input('Please enter your name: ') or '<unknown>' 排序
若是input值爲真則返回,不然返回後者索引
5.while循環ip
name = ''
while not name.strip():
name = input('Please enter your name: ')
print('Hello, {}!'.format(name))
6.for循環
words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
print(word)
7.①迭代字典
d = {'x': 1, 'y': 2, 'z': 3}
for key, value in d.items():
print(key, 'corresponds to', value)
8.並行迭代
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print(names[i], 'is', ages[i], 'years old')
>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
②迭代時獲取索引
index = 0
for string in strings:
if 'xxx' in string:
strings[index] = '[censored]'
index += 1
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
③反向迭代和排序後再迭代
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
8.跳出循環
①break
要結束(跳出)循環,可以使用break。
from math import sqrt
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print(n)
break
②continue
語句continue沒有break用得多。它結束當前迭代,並跳到下一次迭代開頭。
這基本上意味着跳過循環體中餘下的語句,但不結束循環。這在循環體龐大而複雜,且存在多個要跳過它的原
因時頗有用。在這種狀況下,可以使用continue
9.簡單推導
列表推導
>>> [x*x for x in range(10) if x 3 == 0] %
[0, 9, 36, 81]
>>> [(x, y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
元素配對
girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
print([b+'+'+g for b in boys for g in letterGirls[b[0]]])
字典推導
>>> squares = {i:"{} squared is {}".format(i, i**2) for i in range(10)}
>>> squares[8]
'8 squared is 64'
10.三人行
pass
這些代碼不能運行,由於在Python中代碼塊不能爲空。要修復這個問題,只需在中間的代碼
塊中添加一條pass語句便可。
if name == 'Ralph Auldus Melish':
print('Welcome!')
elif name == 'Enid':
# 還未完成……
pass
elif name == 'Bill Gates':
print('Access Denied')
del
在Python中,根本就沒有辦法刪除值,並且你也不須要這樣
作,由於對於你再也不使用的值,Python解釋器會當即將其刪除。
1. exec
函數exec將字符串做爲代碼執行。
>>> exec("print('Hello, world!')")
Hello, world!
>>> from math import sqrt
>>> scope = {}
>>> exec('sqrt = 1', scope)
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
如你所見,可能帶來破壞的代碼並不是覆蓋函數sqrt。函數sqrt該怎樣還怎樣,而經過exec執
行賦值語句建立的變量位於scope中。
請注意,若是你嘗試將scope打印出來,將發現它包含不少內容,這是由於自動在其中添加
了包含全部內置函數和值的字典__builtins__。
>>> len(scope)
2
>>> scope.keys()
['sqrt', '__builtins__']
2. eval
eval是一個相似於exec的內置函數。
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6 + 18 * 2
42
>>> scope = {}
>>> scope['x'] = 2
>>> scope['y'] = 3
>>> eval('x * y', scope)
6
>>> scope = {}
>>> exec('x = 2', scope)
>>> eval('x * x', scope)
4