目錄
一、列表和元組
二、if語句
三、while循環
一、列表和元組
列表元素用中括號( [ ])包裹,元素的個數及元素的值可以改變。元組元素用小括號(( ))包裹,不可以更改(盡管他們的內容可以)。元組可以看成是只讀的列表。通過切片運算( [ ] 和 [ : ] )可以得到子集,這一點與字符串的使用方法一樣。
>>> aList = [1, 2, 3, 4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[:3]
[1, 2, 3]
>>> aList[1] = 5
>>> aList
[1, 5, 3, 4]
元組也可以進行切片運算,得到的結果也是元組(不能被修改):
>>> aTuple = ('robots', 77, 93, 'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[:3]
('robots', 77, 93)
>>> aTuple[1] = 5
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
aTuple[1] = 5
TypeError: 'tuple' object does not support item assignment
二、if語句
與其它語言不同, 條件條達式并不需要用括號括起來。
if 1 < 2:
print('true')
三、while循環
while expression:
while_suite
語句 while_suite 會被連續不斷的循環執行, 直到表達式的值變成 0 或 False; 接著
Python 會執行下一句代碼。 類似 if 語句, Python 的 while 語句中的條件表達式也不需要用括號括起來。