條件敘述與運算子

Python 入門(開發者向)

Jasmin Ludolf

Senior Data Science Content Developer

布林值

# Boolean variable
the_truth = True
print(the_truth)
True
  • 用來做比較
Python 入門(開發者向)

運算子

  • 比較運算子

    • 符號或符號組合
    • 用於比較數值
  • 檢查兩者是否相等

    • ==
Python 入門(開發者向)

檢查是否相等

# Compare if 2 is equal to 3
2 == 3
False
# Check that 2 is not equal to 3
2 != 3
True
  • 常見情境:檢查登入資訊
Python 入門(開發者向)

數值比較運算子

# Is 5 less than 7?
5 < 7
True
# Is 5 less than or equal to 7?
5 <= 7
True
# Is 5 greater than 7?
5 > 7
False
# Is 5 greater or equal to 7?
5 >= 7
False
Python 入門(開發者向)

其他比較

# Is James greater than Brian
"James" > "Brian"
True
  • 字串依字母順序比較
Python 入門(開發者向)

條件敘述

  • 若滿足 if 條件就執行,否則略過
# Check pasta quantities
required_quantity = 500
pasta_quantity = 200


# Compare pasta quantities if pasta_quantity >= required_quantity
Python 入門(開發者向)

條件敘述

  • 若滿足 if 條件就執行,否則略過
# Check pasta quantities
required_quantity = 500
pasta_quantity = 200


# Compare pasta quantities if pasta_quantity >= required_quantity:
Python 入門(開發者向)

條件敘述

  • 若滿足 if 條件就執行,否則略過
# Check pasta quantities
required_quantity = 500
pasta_quantity = 200


# Compare pasta quantities if pasta_quantity >= required_quantity:
print("You have enough pasta!")
Python 入門(開發者向)

縮排

# Check pasta quantities
required_quantity = 500
pasta_quantity = 200


# Compare pasta quantities if pasta_quantity >= required_quantity:
print("You have enough pasta!") # This line is not indented
    print("You have enough pasta!")
    ^
IndentationError: expected an indented block
Python 入門(開發者向)

Elif 敘述

# Check pasta quantities
required_quantity = 500
pasta_quantity = 200

# Compare pasta quantities if pasta_quantity >= required_quantity:
print("You have enough pasta!")
elif pasta_quantity >= 300: print("Nearly enough pasta. Try a smaller portion.")
  • elif 可依需要加入多個!
Python 入門(開發者向)

Else 敘述

# Check pasta quantities
required_quantity = 500
pasta_quantity = 200

# Compare pasta quantities if pasta_quantity >= required_quantity:
print("You have enough pasta!")
elif pasta_quantity >= 300: print("Nearly enough pasta. Try a smaller portion.")
# Otherwise... else: print("Not enough pasta.")
Not enough pasta.
Python 入門(開發者向)

比較運算子小抄

運算子 功能
== 等於
!= 不等於
> 大於
>= 大於或等於
< 小於
<= 小於或等於
關鍵字 功能 用法
if 條件成立時執行 工作流程中的第一步
elif 否則再檢查條件 接在 if 之後
else 以上皆否則執行此動作 接在 elif 之後
Python 入門(開發者向)

一起來練習吧!

Python 入門(開發者向)

Preparing Video For Download...