if-elif-else
if condition:
clause
elif condition:
clause
else:
clause
條件 condition 不用小括弧包起來,條件結束用冒號標示,最後的 else 沒有條件也要用冒號標示。內文區塊 clause 用縮排標示,如果內文區塊裡又有另一個 if-elif-else,得縮排兩次。
import random
target = random.randint(0, 10)
print('guess a number')
guess = int(input())
print('target is ' + str(target))
print('guess is ' + str(guess))
if guess > target:
print('too high')
elif guess < target:
print('too low')
else:
print('you got it')
簡化版 if-else
類似 ?: 運算式,語法如下。是A 如果(if) 這個條件成立 不然(else) 是B常用在預設值處理。
# 條件運算式
class Alias:
def __init__(self, names = None):
self.names = [] if names == None else names
def __str__(self):
return 'Alias with names [' + ','.join(self.names) + ']'
a1 = Alias()
print(a1) # Alias with names []
a2 = Alias(['Nei', 'Banana'])
print(a2) # Alias with names [Nei,Banana]
while
while condition:
clause
條件 condition 不用小括弧包起來,條件結束用冒號標示。內文區塊 clause 用縮排標示,可以在內文區塊使用 break 或 continue 控制流程。
num = 0
while num < 5:
print('current num is ' + str(num))
num += 1
# current num is 0
# current num is 1
# current num is 2
# current num is 3
# current num is 4
for
for condition:
clause
條件 condition 不用小括弧包起來,條件結束用冒號標示。內文區塊 clause 用縮排標示,可以在內文區塊使用 break 或 continue 控制流程。
for num in range(5):
print('current num is ' + str(num))
# current num is 0
# current num is 1
# current num is 2
# current num is 3
# current num is 4
遇到無窮迴圈或冗長程式執行時,可以使用 Ctrl + C 或者 IDLE 裡的 Shell -> Restart Shell(Ctrl + F6) 中斷程式執行或者重新啟動 IDLE。range()
回傳 int 組成的 list,一般與 for 搭配使用。最多可以傳入三個參數:
- start:起始值,包含
- end:結束值,不包含
- stet:步進值,預設為 1,可以使用負數形成遞減 list。
for i in range(5, 0, -1):
print('current i is ' + str(i))
# current i is 5
# current i is 4
# current i is 3
# current i is 2
# current i is 1
搭配三個參數有三種使用方式:- range(start, end, step)
- range(start, end):step 預設為 1
- range(end):start 預設為 0,step 預設為 1
list = [0, 1, 2]
for i in range(len(list)):
print(str(i) + ' > ' + str(list[i]))
# 0 > 0
# 1 > 1
# 2 > 2
Truthy 與 Falsy
在上述的 condition 中除了明確回傳布林值外,也可以回傳 Truthy 與 Falsy 值。- Falsy:0、0.0 與空字串可以視為 False
- Truthy:除了前一點的 0、0.0 與空字串以外,均視為 True
錯誤處理 try-except
print(5 / 0) # ZeroDivisionError: division by zero
def div(m, d):
try:
print(m / d)
except ZeroDivisionError:
print('d can\'t be zero')
div(5, 2) # 2.5
div(5, 0) # d can't be zero
------
---
沒有留言:
張貼留言