標籤:most 語句 eth plain boa assertion erro 條件 tab
條件:
if 條件:
語句塊
elif:
語句塊
else:
語句塊
elif 表示 else if
這居然是合法的!!!1 < x < 2!!!
[python] view plain copy print?
- >>> if 1 < x < 2:
- print(‘True‘)
-
-
- True
and 表示且
[python] view plain copy print?
- >>> if x > 1 and x < 2:
- print(‘True‘)
-
-
- True
or 表示 或
[python] view plain copy print?
- >>> x
- 2
- >>> if x == 2 or x == 3:
- print(x)
-
-
- 2
如果 b 為真則返回a,否則返回 c
a if b else c
[python] view plain copy print?
- >>> ‘True‘ if 1 < x <2 else ‘False‘
- ‘True‘
while 迴圈
while 條件:
語句塊
不需要括弧哦!
[python] view plain copy print?
- >>> x
- 1.2
- >>> while x < 2:
- print(x)
- x += 0.2
-
-
- 1.2
- 1.4
- 1.5999999999999999
- 1.7999999999999998
- 1.9999999999999998
- >>>
經常用 :
[python] view plain copy print?
- while True:
- ....
- if ... :
- break
- ....
for 迴圈
for something in XXXX:
語句塊
即表示對XXXX中的每一個元素,執行某些語句塊,XXXX可以是列表,字典,元組,迭代器等等。
[python] view plain copy print?
- >>> for x in range(0,10):
- print(x*x)
-
-
- 0
- 1
- 4
- 9
- 16
- 25
- 36
- 49
- 64
- 81
這是 for..else...語句
僅在沒有 break 的情況下執行,或者說,只要你沒有 break,它就會執行
[python] view plain copy print?
- >>> for n in range(99,81,-1):
- root = sqrt(n)
- if root == int(root):
- print (n)
- break
- else:
- print ("I didn‘t fint it")
-
-
- I didn‘t fint it
但你應該儘可能使用列表推導式,因為它更方便,清晰
[python] view plain copy print?
- >>> [x*x for x in range(1,5)]
- [1, 4, 9, 16]
- >>> [x**2 for x in range(1,10) if x % 2 ==0]
- [4, 16, 36, 64]
- >>> [(x,y) for x in range(1,3) for y in range(4,6)]
- [(1, 4), (1, 5), (2, 4), (2, 5)]
斷言 assert
後面語句為真,否則出現 AssertionError
用來檢查一個條件,如果它為真,就不做任何事。如果它為假,則會拋出AssertError並且包含錯誤資訊。
例如:
py> x = 23py> assert x > 0, "x is not zero or negative"py> assert x%2 == 0, "x is not an even number"Traceback (most recent call last):File "", line 1, inAssertionError: x is not an even number |
#常用在代碼開頭的注釋
assert
target
in
(x, y, z)
if
target
=
=
x:
run_x_code()
elif
target
=
=
y:
run_y_code()
else
:
assert
target
=
=
z
run_z_code()
pass
pass 表示這裡什麼都沒有,不執行任何操作
如果你的程式還有未完成的函數和類等,你可以先添加一些注釋,然後代碼部分僅僅寫一個 pass,這樣程式可以運行不會報錯,而後期你可以繼續完善你的程式
[python] view plain copy print?
- >>> class Nothing:
- pass
-
- >>>
del
del 刪除的只是引用和名稱,並不刪除值,也就是說,Python 會自動管理記憶體,負責記憶體的回收,這也是 Python 運行效率較低的一個原因吧
[python] view plain copy print?
- >>> x = [1,2,3]
- >>> y = x #x 和 y指向同一個列表
- >>> del x
- >>> x
- Traceback (most recent call last):
- File "<pyshell#41>", line 1, in <module>
- x
- NameError: name ‘x‘ is not defined
- >>> y
- [1, 2, 3]
Python 3 條件、迴圈和assert、pass、del