建立工作流程

Python 入門(開發者向)

Jasmin Ludolf

Senior Data Science Content Developer

複雜工作流程

  • 迴圈處理資料結構
    • forwhile
  • 判斷多個條件
    • ifelifelse>>=<<===!=
  • 更新變數
    • +=
  • 輸出結果
    • print()
Python 入門(開發者向)

「in」關鍵字

  • in = 檢查值是否位於變數/資料結構中
recipe = {"pasta": 500, "tomatoes": 400, 
          "garlic": 15, "basil": 20}

if "pasta" in recipe.keys(): print(True) else: print(False)
True
  • 比逐一迴圈每個鍵更快
Python 入門(開發者向)

「not」關鍵字

  • not = 檢查條件是否「不」成立
  • 用於確認某項目是否缺少
pantry_items = ["flour", "sugar", "olive oil"]

# Check if "salt" is NOT in our pantry if "salt" not in pantry_items: print(True) else: print(False)
True
Python 入門(開發者向)

「and」關鍵字

  • and = 檢查是否同時滿足多個條件
  • 當必須同時符合多個需求時使用
pasta_quantity = 600
olive_oil_quantity = 30

# Check if we have enough of BOTH ingredients if pasta_quantity >= 500 and olive_oil_quantity >= 30: print(True) else: print(False)
True
Python 入門(開發者向)

「or」關鍵字

  • or = 檢查是否有任一(或多個)條件成立
  • 當多個選項任一可接受時使用
pasta_quantity = 600
olive_oil_quantity = 30

# Check if we have enough of EITHER ingredient if pasta_quantity >= 500 or olive_oil_quantity >= 30: print(True) else: print(False)
True
Python 入門(開發者向)

對變數加減值

  • 結合關鍵字與其他技巧來建立複雜流程
ingredients_checked = 0
for ingredient in recipe_list:
    # ingredients_checked = ingredients_checked + 1
    ingredients_checked += 1

items_to_buy = 10 for item in shopping_list: # items_to_buy = items_to_buy - 1 items_to_buy -= 1
  • += 為變數加值,-= 為變數減值
  • 其他更新變數的方法
Python 入門(開發者向)

附加(append)

  • 將符合條件的資訊存入清單
# Create empty list to hold results
shopping_list = []

# Loop through recipe ingredients for ingredient, qty_needed in recipe.items():
# Check if we need to buy it if ingredient not in pantry:
# Add to shopping list shopping_list.append(ingredient)
Python 入門(開發者向)

附加(append)

print(shopping_list)
['tomatoes', 'salt']
Python 入門(開發者向)

一起來練習吧!

Python 入門(開發者向)

Preparing Video For Download...