Bygga ett arbetsflöde

Introduktion till Python för utvecklare

Jasmin Ludolf

Senior Data Science Content Developer

Komplexa arbetsflöden

  • Loopar genom datastrukturer
    • for, while
  • Utvärderar flera villkor
    • if, elif, else, >, >=, <, <=, ==, !=
  • Uppdaterar variabler
    • +=
  • Returnerar utdata
    • print()
Introduktion till Python för utvecklare

Nyckelordet "in"

  • in = kontrollera om ett värde finns i en variabel/datastruktur
recipe = {"pasta": 500, "tomatoes": 400, 
          "garlic": 15, "basil": 20}

if "pasta" in recipe.keys(): print(True) else: print(False)
True
  • Snabbare än att loopa igenom varje nyckel
Introduktion till Python för utvecklare

Nyckelordet "not"

  • not = kontrollera om ett villkor inte är uppfyllt
  • Användbart för att verifiera att något saknas
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
Introduktion till Python för utvecklare

Nyckelordet "and"

  • and = kontrollera om flera villkor är uppfyllda
  • Används när flera krav måste vara uppfyllda
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
Introduktion till Python för utvecklare

Nyckelordet "or"

  • or = kontrollera om ett (eller flera) villkor är uppfyllt
  • Används när något av flera alternativ är godtagbart
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
Introduktion till Python för utvecklare

Addera/subtrahera från variabler

  • Kombinera nyckelord med andra tekniker för att bygga komplexa arbetsflöden
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
  • += adderar till en variabel, -= subtraherar från den
  • Andra sätt att uppdatera variabler
Introduktion till Python för utvecklare

Lägga till element

  • Lagra information som uppfyller specifika kriterier i en lista
# 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)
Introduktion till Python för utvecklare

Lägga till element

print(shopping_list)
['tomatoes', 'salt']
Introduktion till Python för utvecklare

Nu kör vi en övning!

Introduktion till Python för utvecklare

Preparing Video For Download...