如果電話亭 (II)
• 我們用else: 來表示願望沒有成真時要做什麼。
• 願望是指在上面(處在同一層縮排)的 if 後面的條件。
if age < 18:
print('You cannot buy alcohol.')
else:
print('Here you are.')
p.5
35.
如果電話亭 (III)
• 你可以許新願望。
ifage < 6:
print('You should not watch this movie.')
else:
if age < 12:
print('Where are your parents?')
p.5
36.
如果電話亭 (IV)
if nationality== 'Taiwan':
if age >= 20:
if under_guardianship == False:
print('You can vote!')
• 你可以不斷許願。
p.5
37.
成為有邏輯的蛇蛇
運算 運算子 例子
而且and age >= 18 and age < 65
或者 or age < 18 or age >= 65
不是 not not age >= 20
• 「或者」是指至少有一個成立,兩個都成立也算。
p.3
38.
如果電話亭 (V)
if nationality== 'Taiwan' and age >= 20 and under_guardianship == False:
print('You can vote!')
else:
print('You cannot vote.')
• 用點邏輯就能讓滿滿的願望變成簡單的生活。
• 當邏輯較為複雜時,我們可以用小括號指定順序。
p.5
39.
如果電話亭 (VI)
• 我們用elif 新條件: 來表示舊願望沒有成真時所許的新願望。
if age < 6:
print('You should not watch this movie.')
elif age < 12:
print('Where are your parents?')
p.5
40.
如果電話亭 (VII)
if age< 6:
print('You should not watch this movie.')
elif age < 12:
print('Where are your parents?')
else:
print('Here is your ticket.')
• 總結。
p.5
41.
表與裡
if age <6:
print('You should not watch this movie.')
elif age < 12:
print('Where are your parents?')
else:
print('Here is your ticket.')
print('Bye-bye.')
p.5
教蛇蛇做功德 (I)
• 我們用while 條件: 來表示做功德的開始。
• 蛇蛇會一直做功德,直到條件不成立為止。
times = 3
while times > 0:
print('I am working!')
times = times - 1
p.6
49.
教蛇蛇做功德 (II)
• 要注意while 條件: 中的條件必須要在做功德的途中被改變,
否則就會不斷做功德。
times = 0
while times < 10:
print('I am working!')
times = times + 1
times = 0
while times < 10:
print('I am working!')
做十次功德 做一生功德
p.6
50.
明訂職權範圍
• 為了避免蛇蛇做太多功德,我們常常會幫蛇蛇訂定職權範圍。
• 用for 成員 in 容器: 限定做功德的範圍。
• 用中括號包起來的資料稱為序列。
friends = ['Alice', 'Bob', 'Charlie', 'Dave', 'Eve']
for friend_name in friends:
print('Hi, ' + friend_name)
p.6
51.
明訂工作次數
• 用 range(次數)訂定做功德的次數。
for number in range(10):
print(number)
if number % 2 == 0:
print('It is an even number!')
else:
print('It is an odd number!')
p.7
52.
能做功德的就是好蛇蛇
for times inrange(10):
print('I am working!')
times = 0
while times < 10:
print('I am working!')
times = times + 1
p.6