Python 的 if / else 寫法跟其他程式語言類似, 可以在條件後面加上 “:” 字符, 或者用 ( ) 包圍著條件後加上 “:” 也可以, 語法格式是這樣:
1 2 3 4 |
if (condition): code1 else: code2 |
例如:
1 2 3 4 5 6 7 8 |
#!/usr/bin/python age = 18 if (age >= 18): print("Adult!") else: print("Child!") |
上面會檢查變數 age 是否等如或大於 18, 判斷後輸出 “Adult!” 或 “Child!”.
如果要把兩個條件一同判斷, 需要用 AND 或 OR 連接, 語法是這樣:
1 2 3 4 |
if (cond1 AND/OR COND2) AND/OR (cond3 AND/OR cond4): code1 else: code2 |
例如要判斷年齡是否 8 – 12 歲, 可以用以下寫法:
1 2 3 4 5 6 |
#!/usr/bin/python if ((age >= 8) and (age <= 12)): print("Allowed, Welcome!") else: print("NOT allowed!") |