构建工作流

Python for Developers 入门

Jasmin Ludolf

Senior Data Science Content Developer

复杂工作流

  • 遍历数据结构
    • forwhile
  • 评估多个条件
    • ifelifelse>>=<<===!=
  • 更新变量
    • +=
  • 返回输出
    • print()
Python for Developers 入门

"in" 关键字

  • in = 检查某值是否在变量/数据结构中
recipe = {"pasta": 500, "tomatoes": 400, 
          "garlic": 15, "basil": 20}

if "pasta" in recipe.keys(): print(True) else: print(False)
True
  • 比遍历每个键更快
Python for Developers 入门

"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 for Developers 入门

"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 for Developers 入门

"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 for Developers 入门

变量加减

  • 将关键字与其他技术结合,构建复杂工作流
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 for Developers 入门

追加(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 for Developers 入门

追加(append)

print(shopping_list)
['tomatoes', 'salt']
Python for Developers 入门

Passons à la pratique !

Python for Developers 入门

Preparing Video For Download...