條件 循環及其他語句
import的更多信息
import可以從模塊導入函數,可以在語句末尾增加as子句,提供別名(可爲函數或模塊提供別名)
>>> import math
>>> math.sqrt(4)
2.0
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
賦值
- 序列解包
將多個值的序列解開,然後放到變量的序列中。python3中有另外的特性可以像在函數的參數列表中一樣使用星號運算符。
>>> d1 = {"d1":"1","d2":"2"}
>>> key,value = d1.popitem()
>>> key
'd2'
>>> value
'2'
>>> a,b,*test = [1,2,3,4,5]
>>> a
1
>>> b
2
>>> test
[3, 4, 5]
- 鏈式賦值
將同一個值賦給多個變量 - 增量賦值
將表達式下x = x + 1寫成x += 1這種寫法叫增量賦值,對於*,/,%等標準運算符都適用,使代碼緊湊,易讀。
>>> x = 3
>>> x *= 2
>>> x
6
>>> fnord = "foo"
>>> fnord += "bar"
>>> fnord *= 2
>>> fnord
'foobarfoobar'
條件和條件語句
- 布爾值
以下值在作爲布爾表達式的時候,會被解釋器看作假(False)
False None 0 " " () [] {}(都爲假值,本身不相等)
換句話說,也就是標準的False和None、所有類型的數字0(浮點型,長整型和其他類型)、空序列以及空的字典都爲假,其他一切都被解釋爲真。也就是python中的所有值都能被解釋爲布爾值
>>> bool("test")
True
>>> bool("")
False
>>> bool(0)
False
>>> bool([] == "")
False
- 條件執行和if語句
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
python中的比較運算符
表達式 | 描述 |
---|---|
x == y | x等於y |
x < y | x小於y |
x > y | x大於y |
x >= y | x大於等於y |
x <= y | x小於等於y |
x != y | x不等於y |
x is y | x和y是同一個對象 |
x is not y | x和y不是同一個對象 |
x in y | x是y容器的成員 |
x not in y | x不是y容器的成員 |
- 斷言
你可以要求某些條件必須爲真,語句的關鍵字就是assert
>>> age = 10
>>> assert 0 < age <10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 0 < age <100
>>>
循環
- while循環
x =1
while x<= 10:
print(x)
x +=1
- for循環
words = ["this","is","an","parrot"]
for word in words:
print(word)
for number in range(0,10):
print(number)
- 循環遍歷字典元素
# 遍歷字典元素
d = {"x":"1","y":"2","z":"3"}
for key in d:
print(key,"=",d[key])
#使用序列解包 便利
for key, value in d.items():
print (key,"=",value)
- 迭代
# 並行迭代
names = ["a1","a2","a3","a4"]
ages = [22,24,26,23]
for i in range(len(names)):
print(names[i], "is", ages[i], "years oid")
# 使用內建函數zip來並行迭代
for name, age in zip(names,ages):
print(name, "is", age, "years old")
# zip可以用來處理不等長的數列
for x, y in zip(range(5), range(100)):
print (x,y)
- 跳出循環
break
from math import sqrt
# break跳出循環
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print(n)
break
continue
# continue 結束當前循環,跳到下一輪循環
for n in range(0, 10):
if n%2 == 0:
continue
else:
print(n)
列表推導式
利用其他列表創建新的列表的一種方式,類似於for循環
# 列表推導式
a = [x*x for x in range(10)]
print(a)
b = [x*x for x in range(10) if x % 3 == 0]
print(b)
c = [(x, y) for x in range(3) for y in range(2)]
print(c)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 9, 36, 81]
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
pass、del和exec
- pass
程序什麼事情都不用做,就需要pass語句。python中空代碼塊是非法的
# pass
flage = -1
if flage < 0:
print("小於0")
elif flage >0:
# 還未完成。。。
pass
else:
print("0")
- del
del語句會移除一個對象的引用,也會移除那個名字(刪除的只是名字,而不是本身的值,python沒辦法刪除值,有解釋器負責內存回收)
>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = ["hello python"]
>>> y =x
>>> del x
>>> y
['hello python']
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
- exec和eval
exec執行一個字符串語句。動態的創造python代碼
eval會計算python表達式(以字符串形式書寫)
>>> exec("print('hello!')")
hello!
>>> eval("6+8*2")
22