運算符
is:同一性運算符
x is y
true
in:成員資格運算符
name = input('What is your name?')
if 's' in name
print ('Your name contains the letter "s" ')
else:
print ('Your name does not contain the letter "s"')
斷言
If語句有個非常有用的“近親”,它的工作方式多少有點像下面這樣(僞代碼):
if not condition:
crash program
如果需要確定程式中的某個條件一定為真才能讓程式正常工作的話,assert語句就有用了,它可以在程式中置入檢查點。
條件後可以添加字元串,用來解釋斷言:
age = -1
assert = 0 < age < 10, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1,in ?
AssertonError: The age must be realistic
判斷語句
Python裡面判斷語句第一句結尾要加個 :
while語句用來在任何條件為真的情況下重複執行一個代碼塊。
for循環:
比如要為一個集合(序列和其他可疊代對象)的每個元素都執行一個代碼塊。注:可疊代對象是指可以按次序疊代的對象(也就是用于for循環中的)
比如:
words = ['this','is','an','ex','parrot']
for word in words:
print (word)
輸出結果為:
this
is
an
ex
parrot
因為疊代(循環的另外一種說法)某範圍的數字是很常見的,是以有個内建的範圍函數供使用:
range(0,10)
[0,1,2,3,4,5,6,7,8,9,10]
Range函數的工作方式類似于分片。它包含下限(本例中為0),但不包含上限(本例中為10)。
如果希望下限是0,可以隻提供上限,比如:
range(10)
下面程式會列印1~100的數字:
for number in range(1,101):
print (number)
提示:如果能使用for循環,就盡量不用while循環。
循環周遊字典元素
一個簡單的for語句就能周遊字典的所有鍵,就像周遊通路序列一樣:
d = {'x':1, 'y':2, 'z':3}
for key in d:
pirnt (key, 'corresponds to', d[key]
輸出結果:
x corresponds 1 y corresponds 2
z corresponds 3