條件、循環及其他語句
1.自定義分隔符:
>>> print("I", "wish", "to", "register", "a", "complaint", sep="_",end=‘‘) seq 默認為‘ ’end=‘\n‘
I_wish_to_register_a_complaint
2.用作布爾表達式(如用作if語句中的條件)時,下面的值都將被解釋器視為假:
False , None , 0, " ", ( ) ,[ ] ,{ } 換而言之,標準值False和None、各種類型(包括浮點數、復數等)的數值0、空序列(如空字符串、空元組和空列表)以及空映射(如空字典)都被視為假,而其他各種值都被視為真,包括特殊值True。
3.條件表達式:
status = "friend" if name.endswith("Gumby") else "stranger"
如果為真 ,提供的第一個值‘friend‘,否則則為假 ,提供後面一個值‘stranger‘
4.短路邏輯和條件表達式
name = input(‘Please enter your name: ‘) or ‘<unknown>‘
如果input值為真則返回,否則返回後者
5.while循環
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
條件、循環及其他語句