ZTM

Run Settings
LanguagePython
Language Version
Run Command
''' def final_amount(check): # add a 25% tip return round(check * 1.25) print(final_amount(100)) ''' ''' #Compute the daily totals spent after adding a 25% tip each day. def final_amount(check): return check * 1.25 daily_checks = [50, 100, 85, 120] # compute totals for these days daily_totals = [final_amount(day) for day in daily_checks] print("Daily Totals:", daily_totals) ''' ''' #Compute the total spent over the recorded days, including tips. def final_amount(check): return check * 1.25 daily_checks = [50, 100, 85, 120] #daily_totals = [final_amount(check) for check in daily_checks] #weekly_total = sum(daily_totals) #or weekly_total = sum([final_amount(check) for check in daily_checks]) print("Weekly total:", weekly_total) ''' ''' #Replace lines 14 and 15 with a single line that does the same thing: #applying compost first, then mulch. def compost(soil): if soil < 15: return soil + 10 else: return soil + 5 def mulch(soil): new_soil = soil + 3 if new_soil > 25: new_soil *= 1.2 return round(new_soil) def mulch_after_compost(soil): #new_soil = compost(soil) #return mulch(new_soil) return mulch(compost(soil)) print("Mulch after compost:", mulch_after_compost(20)) ''' ''' #Make this function apply mulch first, then compost. def compost(soil): if soil < 15: return soil + 10 else: return soil + 5 def mulch(soil): new_soil = soil + 3 if new_soil > 25: new_soil *= 1.2 return round(new_soil) def compost_after_mulch(soil): # apply compost after mulch return compost(mulch(soil)) print("Compost after mulch:", compost_after_mulch(20)) ''' ''' def compost(soil): if soil < 15: return soil + 10 else: return soil + 5 def mulch(soil): new_soil = soil + 3 if new_soil > 25: new_soil *= 1.2 return round(new_soil) def mulch_after_compost(soil): return mulch(compost(soil)) def compost_after_mulch(soil): return compost(mulch(soil)) print("Mulch after compost:", mulch_after_compost(20)) print("Compost after mulch:", compost_after_mulch(20)) ''' ''' def compost(soil): if soil < 15: return soil + 10 else: return soil + 5 def mulch(soil): new_soil = soil + 3 if new_soil > 25: new_soil *= 1.2 return round(new_soil) def fruits_from_soil(soil): return round(soil / 10) def mulch_after_compost(soil): return mulch(compost(soil)) def compost_after_mulch(soil): return compost(mulch(soil)) daily_soil = [10,20,30,40,50] #composted_soil = [compost(soil) for soil in daily_soil] #improved_soil = [mulch(soil) for soil in composted_soil] #or #improved_soil = [mulch(compost(soil)) for soil in daily_soil] #or #improved_soil1 = [mulch_after_compost(soil) for soil in daily_soil] #improved_soil2 = [compost_after_mulch(soil) for soil in daily_soil] fruits = 92 improved_soil = [mulch(compost(soil)) for soil in daily_soil] #daily_fruits = [fruits_from_soil(mulch(compost(soil))) for soil in daily_soil] #fruits += sum(daily_fruits) #or daily_fruits = [fruits_from_soil(soil) for soil in improved_soil] fruits += sum(daily_fruits) #print("Final soil:", improved_soil) #print("Mulch after compost:", improved_soil1) #print("Compost after mulch:", improved_soil2) print(daily_fruits) print("Fruits:", fruits) ''' ''' #A latte costs 40 coins. #There's a 5 coin discount, applied before adding the tax. #Replace lines 8 and 9 with a single line that does the same thing. def discount(price): return price - 5 def add_tax(price): return price * 1.12 def tax_after_discount(price): #reduced_price = discount(price) #return add_tax(reduced_price) return add_tax(discount(price)) print("Final cost:", tax_after_discount(40)) ''' ''' #A latte costs 40 coins. #There's a 5 coin discount. #Apply the tax before applying the discount. def discount(price): return price - 5 def add_tax(price): return price * 1.12 def discount_after_tax(price): # apply discount after adding tax return discount(add_tax(price)) print("Final cost:", discount_after_tax(40)) ''' ''' #Use the sum function to add up how many cupcakes were sold. daily_cupcakes = [8, 12, 6, 20, 4] # use sum to calculate the total total_cupcakes = sum(daily_cupcakes) print(total_cupcakes) ''' ''' #Use the rental_fee function to build a list of daily fees for 5 days. def rental_fee(bikes): return bikes * 12 daily_bikes = [5, 3, 10, 2, 4] daily_fees = [] for bikes in daily_bikes: cost = rental_fee(bikes) # append cost to daily_fees daily_fees.append(cost) print(daily_fees) ''' ''' #Compute the total rental cost for 5 days, #where each day has a number of bikes that cost 12 dollars each. def rental_fee(bikes): return bikes * 12 daily_bikes = [5, 3, 10, 2, 4] daily_fees = [] for bikes in daily_bikes: cost = rental_fee(bikes) daily_fees.append(cost) # add up all the fees total_cost = sum(daily_fees) print(total_cost) ''' ''' #Use the ticket_cost function to compute the daily costs for 5 days. def ticket_cost(num_tickets): return num_tickets * 12 daily_tickets = [10, 12, 5, 7, 9] # compute daily_costs daily_costs = [ticket_cost(day) for day in daily_tickets] print(daily_costs) ''' ''' #Compute the total revenue for 5 days, #where each movie ticket costs 12 dollars. def ticket_cost(num_tickets): return num_tickets * 12 daily_tickets = [10, 12, 5, 7, 9] daily_costs = [ticket_cost(tickets) for tickets in daily_tickets] # compute the total revenue revenue = sum(daily_costs) print(revenue) ''' ''' #Compute the daily totals spent after adding a 25% tip each day. def final_amount(check): return check * 1.25 daily_checks = [50, 100, 85, 120] # compute totals for these days daily_totals = [final_amount(checks) for checks in daily_checks] print("Daily Totals:", daily_totals) ''' ''' #Compute the total spent over the recorded days, including tips. def final_amount(check): return check * 1.25 daily_checks = [50, 100, 85, 120] daily_totals = [final_amount(check) for check in daily_checks] # sum all daily totals to find the total cost weekly_total = sum(daily_totals) print("Weekly total:", weekly_total) ''' ''' #Servers prefer tips after the 7% tax. #Compute the final bill with a 20% tip after tax. def total_with_tax(check): return check * 1.07 def add_tip(check): return check * 1.20 # Compute final bill when tipping after 7% tax # for a 130 check #taxed_check = total_with_tax(130) #final_bill = add_tip(taxed_check) #or final_bill = add_tip(total_with_tax(130)) print("Final bill:", final_bill) ''' ''' #For the 3 checks, compute the tip based on the after-tax total. def total_with_tax(check): return check * 1.07 def add_tip(check): return check * 1.20 daily_checks = [130, 90, 150] # Compute bills # when tipping after 7% tax daily_taxed = [total_with_tax(bill) for bill in daily_checks] final_bills = [add_tip(bill) for bill in daily_taxed] #or #final_bills = [add_tip(total_with_tax(checks)) for checks in daily_checks] print("Final bills:", final_bills) ''' ''' #A bag of coffee beans costs 50 coins. #There's an 8 coin discount. #Apply the tax before applying the discount. def discount(price): return price - 8 def add_tax(price): return price * 1.10 def discount_after_tax(price): # apply discount after adding tax return discount(add_tax(price)) print("Final cost:", discount_after_tax(50)) ''' ''' #Which ordering gives the lower final cost? def discount(price): return price - 8 def add_tax(price): return price * 1.10 def discount_after_tax(price): return discount(add_tax(price)) def tax_after_discount(price): return add_tax(discount(price)) print("Discount after tax:", discount_after_tax(50)) # Discount after tax: 47.0 print("Tax after discount:", tax_after_discount(50)) # Tax after discount: 46.2 ''' ''' #Let’s use a dictionary to map fruit to prices. #Pears cost 2 gems. Update the function. def price(fruit): if fruit == "pear": return 2 total = price("pear") print("Price of pears:", total) ''' ''' #Apples cost 1 gem. Update the function. def price(fruit): if fruit == "pear": return 2 # Apples cost 1 gem each if fruit == "apple": return 1 total = price("apple") print("Price of apples:", total) ''' ''' #Oranges cost 4 gems. Update the function. def price(fruit): if fruit == "pear": return 2 elif fruit == "apple": return 1 # Oranges cost 4 gems each elif fruit == "orange": return 4 total = price("orange") print("Price of oranges:", total) ''' ''' #Replace the function with a dictionary. #def price(fruit): fruit_prices = { "pear": 2, "apple": 1, "orange": 4, } total = fruit_prices["orange"] print("Price of oranges:", total) ''' ''' #Use the dictionary to get the price of a pear. fruit_prices = { "pear": 2, "apple": 1, "orange": 4, } # Look up the price of a pear total = fruit_prices["pear"] print("Price of pears:", total) ''' ''' #Calculate the total price of 1 pear and 1 orange. fruit_prices = { "pear": 2, "apple": 1, "orange": 4, } # Sell a pear and an orange gems = fruit_prices["pear"] + fruit_prices["orange"] print("Gems:", gems) ''' ''' #Use the dictionary to look up the price of a coffee. drink_prices = { "latte": 40, "coffee": 20, "juice": 30, "smoothie": 75, } # Get price of coffee total = drink_prices["coffee"] print("Coffee price:", total) ''' ''' drink_prices = { "latte": 40, "coffee": 20, "juice": 30, "smoothie": 75, } # Get price of a latte and a smoothie total = drink_prices["latte"] + drink_prices["smoothie"] print("Total price:", total) ''' ''' # The dictionary (accessible globally) FRUIT_PRICES = { "pear": 2, "apple": 1, "orange": 4, } def price(fruit): # Use the .get() method on the dictionary # Key = fruit (the input) # Default = None (what to return if the fruit isn't found) return FRUIT_PRICES.get(fruit, None) # --- Test the function --- total_pear = price("pear") total_banana = price("banana") print("Price of pears:", total_pear) print("Price of bananas:", total_banana) ''' ''' INVENTORY = { "sword": 150, "shield": 80, "potion": 10 } def get_price(item): """ Looks up the price of an item. - If the item is "gem," return a fixed price of 500 (using an IF). - If the item is in INVENTORY, return its price. - If the item is not found, return None. """ # 1. Handle the "gem" special case # Your IF statement here... if item == 'gem': return 500 # 2. Handle standard items and missing items efficiently # Use a dictionary method to look up items from INVENTORY # and return None if the item isn't found. # Your dictionary method call here... return INVENTORY.get(item, None) # --- Test Cases (Uncomment and run after you complete the function) --- print(f"Sword price: {get_price('sword')}") # Should output: 150 print(f"Gem price: {get_price('gem')}") # Should output: 500 print(f"Axe price: {get_price('axe')}") # Should output: None ''' ''' # This program checks for donuts in line 9. What happens? loop_num = 1 energy = 0 daily_snacks = ["🍩","🥕","🥕"] for snack in daily_snacks: print(f"--- Loop {loop_num} ---") print(f"index being checked: '{snack}'") print() sugar = 1 fiber = 1 if snack == "🥕": fiber = 2 energy += sugar + fiber if snack == "🍩": sugar = 3 loop_num += 1 print("Fiber:", fiber) print("Sugar:", sugar) print("Energy:", energy) ''' ''' inventory = { "pear": 51, "apple": 17, } count = inventory["pear"] print("Number of pears:", count) count = inventory["apple"] print("Number of apples:", count) ''' ''' #Compute the total number of fruits. inventory = { "pear": 51, "apple": 17, "orange": 45, } # add up all the fruits count = inventory["pear"] + inventory["apple"] + inventory["orange"] #or count = sum(inventory.values()) print("Total fruits:", count) ''' ''' #Using the price dictionary, calculate the value of all the pears. inventory = { "pear": 51, "apple": 17, "orange": 45, } price = { "pear": 2, "apple": 1, "orange": 4, } # compute total value of pears value = inventory["pear"] * price["pear"] print("Total value:", value, "gems") ''' ''' #Let's track expenses. #Add an entry for concerts, with a value of 150 coins. expenses = { "food": 200, "drinks": 120, "concerts": 150 } coins = expenses["concerts"] print("Concert expenses:", coins) ''' ''' #How much was spent on food and drinks combined? expenses = { "food": 200, "drinks": 120, "concerts": 150, } # food and drink expenses coins = expenses["food"] + expenses["drinks"] print("Food and drinks:", coins) ''' ''' #Add up the total expenses. expenses = { "food": 200, "drinks": 120, "concerts": 150, } # total expenses #coins = expenses["food"] + expenses["drinks"] + expenses["concerts"] coins = sum(expenses.values()) print("Total expenses:", coins) ''' #ZTM Dictionary Code: #Dictionary keys needs to be immutable #Usually a key for a dictionary is something descriptive like a string #A key has to be unique, there can only be one key, a duplicate will override the previous one. ''' dictionary = { 'basket': [1,2,3], 'greet': 'hello', } print(dictionary['basket']) user = { 'basket': [1,2,3], 'greet': 'hello', } print(user.get('age')) print(user.get('age',55)) print(user.get('greet')) #another way to create a dictionary which is not very wildly used user2 = dict(name='JohnJohn') print(user2) ''' ''' user = { 'basket': [1,2,3], 'greet': 'hello', 'age': 20, } #print('size' in user) #print('age' in user.keys()) ##print('hello' in user.values()) #print(user.items()) #print() #user2 = user.copy() #print(user2) #print(user.clear()) #user.clear() #print(user) #print(user.pop('age')) #pop returns the value of what gets removed #print(user.popitem()) #Not random. This function removes the last key:value pair that was inserted into the dictionary. #useful to destructively iterate over a dictionary print(user.update({'age': 55})) print(user) ''' # Brilliant Code: #Warmup code practice ''' #How many cars are listed? cars = ["red", "blue", "black", "white", "blue", "red", "green", "blue", "silver"] count = 0 for car in cars: count += 1 print("Total cars:", count) # The loop increments once for each car. There are 9 cars, so count is 9. ''' ''' #How many cars are red or blue? cars = ["red", "blue", "black", "white", "blue", "red", "green", "blue", "silver"] color_count = 0 for car in cars: if car == "red" or car == "blue": color_count += 1 print("Red or blue cars:", color_count) #There are 2 red and 3 blue cars, so the OR condition is true 5 times. ''' ''' #Why does this program count 0 red-or-blue cars? cars = ["red", "blue", "black", "white", "blue", "red", "green", "blue", "silver"] color_count = 0 for car in cars: if car == "red" and car == "blue": color_count += 1 print("Red or blue cars:", color_count) #A car can’t be both red AND blue. So the condition in line 4 is never true. ''' # Brilliant Code: #Dictionaries ''' #Last time, we sold 5 pears. Update the dictionary so 46 pears remain. inventory = { "pear": 51, "apple": 17, "orange": 45, } count = inventory["pear"] print("Number of pears:", count) ''' ''' #Reduce the pear count by 5 without redefining the dictionary. inventory = { "pear": 51, "apple": 17, "orange": 45, } # reduce pear inventory by 5 #Increase the apple count by 10. inventory["pear"] -= 5 inventory["apple"] += 10 inventory["orange"] -= 7 print(inventory) #Compute the total number of fruits currently in stock. #count = inventory["pear"] + inventory["apple"] + inventory["orange"] count = sum(inventory.values()) print("Total fruits:", count) price = { "pear": 2, "apple": 1, "orange": 4, } gems = 16 gems += 7 * price["orange"] print("Gems:", gems) #The expression inventory["pear"] can be incremented or decremented, just like a variable. #Line 7 reduces its value by 5 to reflect that 5 pears were sold. ''' ''' #There's a new dog! Update the pets dictionary. pets = { "chickens": 9, "dogs": 3, "rabbits": 5, } pets["dogs"] += 1 print(pets) ''' ''' #Three of the chickens escaped. Update the pets dictionary. pets = { "chickens": 9, "dogs": 3, "rabbits": 5, } pets["dogs"] += 1 # reduce chickens by 3 pets["chickens"] -= 3 print(pets) ''' ''' #Subtract 20 gems to pay for a crate of lemons. inventory = { "pear": 46, "apple": 27, "orange": 38, } gems = 44 # spend 20 gems on lemons gems -= 20 print("Gems:", gems) ''' ''' #Redefine the inventory to record 30 lemons. #adds the key “lemon” to the inventory dictionary and sets its value to 30. inventory = { "pear": 46, "apple": 27, "orange": 38, # add 30 lemons } inventory["lemons"] = 30 print(inventory) ''' ''' #Set lemon price to 3 gems in the price dictionary. inventory = { "pear": 46, "apple": 27, "orange": 38, } inventory["lemon"] = 30 price = { "pear": 2, "apple": 1, "orange": 4, } # set price of lemons to 3 price["lemon"] = 3 print(price) ''' ''' #Let's sell some fruit. Reduce pear count by 3 and lemon count by 4. inventory = { "pear": 46, "apple": 27, "orange": 38, } inventory["lemon"] = 30 price = { "pear": 2, "apple": 1, "orange": 4, } price["lemon"] = 3 # sell 3 pears # and 4 lemons inventory["pear"] -= 3 inventory["lemon"] -= 4 gems = 24 #gems += price["pear"] * 3 + price["lemon"] * 4 #Not prefered way of writing gems += 3*price["pear"] + 4*price["lemon"] print(inventory) print("Gems:", gems) ''' ''' # total expenses coins = expenses["food"] + expenses["drinks"] + expenses["concerts"] coins = sum(expenses.values()) ''' ''' #Add 5 scary costumes to the collection. #Add 8 medieval costumes to the collection. costumes = { "animals": 7, "starwars": 10, } # add 5 scary costumes costumes["scary"] = 5 # add 8 medieval costumes costumes["medieval"] = 8 # add 3 more Star Wars costumes costumes["starwars"] += 3 print(costumes) ''' ''' #Let's use a loop to iterate over a dictionary and simplify tracking inventory. #Loop through the inventory dictionary. inventory = { "pear": 43, "apple": 27, "orange": 38, "lemon": 26, } # loop through the dictionary for fruit in inventory: print(fruit) #Python's for loop can run through the keys of a dictionary. #When a Python for loop runs through a dictionary, #the loop index runs through all the key values. ''' ''' print(dictionary['basket']) user = { 'basket': [1,2,3], 'greet': 'hello', } print(user.get('age')) print(user.get('age',55)) print(user.get('greet')) ''' ''' #Inside the loop, set stock to the number of the current fruit in the inventory. inventory = { "pear": 43, "apple": 27, "orange": 38, "lemon": 26, } for fruit in inventory: # set number of fruits #stock = inventory.get(fruit) stock = inventory[fruit] print(fruit, stock) #The inventory dictionary stores the number of each fruit in stock. #As the fruit variable changes each time through the loop, #inventory[fruit] gives the corresponding number of fruit. ''' ''' #Let's add up the inventory. #First, set a starting value. inventory = { "pear": 43, "apple": 27, "orange": 38, "lemon": 26, } inventory["pear"] -= 10 price = { "pear": 2, "apple": 1, "orange": 4, "lemon": 3, } gems = 42 gems += 10*price["pear"] # set starting value total_fruits = 0 #The total_fruits variable will store the total inventory count. #We start this counter at zero before running the loop to add values to it. for fruit in inventory: stock = inventory[fruit] print(fruit, stock) #Update the fruit counter inside the loop. total_fruits += stock print("Total fruits:", total_fruits) #Each time through the loop, line 10 updates stock to count the number of the current fruit type. #Line 11 adds this value to the total_fruits counter. #When the loop finishes, total_fruits contains the total number of fruits in the inventory. print("Gems:", gems) ''' ''' #Set a loop to run through the shell collection and print each shell type. collection = { "conch": 17, "clam": 24, "scallop": 36, "coral": 21, } # loop through the dictionary for shell_type in collection: print(shell_type) ''' ''' #Set shells to count the number of shells of each type. collection = { "conch": 17, "clam": 24, "scallop": 36, "coral": 21, } for shell_type in collection: # set number of shells shells = collection[shell_type] print(shell_type, shells) # For each different shell_type key, collection[shell_type] gives the number of shells. ''' ''' #Update the counter to compute the total number of shells in the collection. collection = { "conch": 17, "clam": 24, "scallop": 36, "coral": 21, } total_shells = 0 for shell_type in collection: shells = collection[shell_type] # update counter total_shells += shells print("Total shells:", total_shells) #The total_shells variable stores the total number of shells. #Each time through the loop, line 11 adds the category total, shells, to total_shells. ''' ''' #Look up the price of mushrooms from the dictionary. pizza_toppings = { "pepperoni": 50, "mushrooms": 70, "olives": 30, "anchovies": 90, } # get the price of mushrooms total = pizza_toppings["mushrooms"] print("Mushrooms cost:", total) #Compute the total price of pepperoni and anchovies. #add the price of pepperoni to the price of anchovies total_p_and_a = pizza_toppings["pepperoni"] + pizza_toppings["anchovies"] print("Total cost:", total_p_and_a) #To get the price of a topping, reference the dictionary by #name followed by the key in square brackets. #To add the price of two toppings, use the dictionary with each topping's name #in square brackets, then add them. ''' ''' #How many coins were spent on books and snacks combined? expenses = { "books": 45, "snacks": 120, "gifts": 75, } # total cost for reading and snacking coins = expenses["books"] + expenses["snacks"] print("Reading and snacking:", coins) #Add up the total expenses. # total expenses #Total_coins = expenses["books"] + expenses["snacks"] + expenses["gifts"] Total_coins = sum(expenses.values()) print("Total expenses:", Total_coins) ''' ''' #Let's add two new cats. Update the dictionary to reflect this. pets = { "goldfish": 6, "cats": 2, "parrots": 2, } # add 2 cats pets["cats"] += 2 print(pets) #Incrementing the expression pets["cats"] #by 2 increases the value of cats in the dictionary. #One of the parrots flew away. Update the dictionary to reflect losing 1 parrot. pets["parrots"] -= 1 print(pets) ''' ''' #Add 4 wizard costumes to the collection. costumes = { "animals": 2, "starwars": 3, } costumes["superhero"] = 6 # add 4 wizard costumes costumes["wizard"] = 4 print(costumes) #Line 7 creates a new dictionary key called "wizard" #and sets its corresponding value to 4. #Add 2 additional animal costumes. # add 2 more animal costumes costumes["animals"] += 2 print(costumes) ''' ''' #Set quantity to the number of each item in stock. supplies = { "pens": 12, "markers": 6, "glue_sticks": 9, "paper_pads": 3, } total_items = 0 for item_name in supplies: # set quantity quantity = supplies[item_name] #print(item_name, quantity) #Add up all the items to find the total supply count. #update total #total_items = sum(supplies.values()) #they are all correct total_items += quantity #total_items += supplies[item_name] print("Total items:", total_items) ''' #WARM UP CODE ''' #This program checks for pigs in line 5. #What is the value of pigs when line 10 runs? coins = 3 visitors = ["🐓","🐖","🐄"] for animal in visitors: pigs = 0 if animal == "🐖": #LINE 5 pigs = 1 cows = 0 if animal == "🐄": cows = 1 coins += pigs + cows #LINE 10 print(coins) ''' ''' #How many social emails (friend or family) are counted? social_count = 0 emails = ['work', 'friend', 'spam', 'family', 'work', 'spam', 'friend'] for email in emails: if email == 'friend' or email == 'family': social_count += 1 print("Social:", social_count) ''' ''' #Processing Dictionaries #The inventory is stocked with fruit. #Let's add up its total value using loops. #Loop through the inventory. inventory = { "pear": 33, "apple": 27, "orange": 38, "lemon": 26, } price = { "pear": 2, "apple": 1, "orange": 4, "lemon": 3, } total_value = 0 # loop through inventory for fruit in inventory: #individual_value = inventory[fruit] #total_value += individual_value #print(fruit, end = " ") #print(individual_value) #total_value = sum(inventory.values()) #print(total_value) ''' #GEMINI example ''' sales_data = { "Monday": [10, 5, 15], # 30 total "Tuesday": [20, 10], # 30 total } daily_totals = {} for day, transactions in sales_data.items(): # Here, sum() is correctly used to calculate the sum of the inner list (transactions) daily_totals[day] = sum(transactions) # daily_totals will be {"Monday": 30, "Tuesday": 30} print(daily_totals) ''' ''' #For each fruit, store how many are in stock. inventory = { "pear": 33, "apple": 27, "orange": 38, "lemon": 26, } price = { "pear": 2, "apple": 1, "orange": 4, "lemon": 3, } for fruit in inventory: # set number of fruit stock = inventory[fruit] #print(fruit, stock) #The inventory dictionary stores the number of each fruit in stock. #As the fruit variable changes each time through the loop, #inventory[fruit] gives the corresponding number of fruit. #Store the unit price for each fruit. # set price of fruit #for fruit in price: unit_price = price[fruit] print(fruit, stock, unit_price) #The price dictionary stores the unit price of each type of fruit. #As the fruit variable changes each time through the loop, #price[fruit] gives the corresponding unit price. ''' ''' #Compute the total value for each fruit. inventory = { "pear": 33, "apple": 27, "orange": 38, "lemon": 26, } price = { "pear": 2, "apple": 1, "orange": 4, "lemon": 3, } for fruit in inventory: stock = inventory[fruit] unit_price = price[fruit] # set value value = stock * unit_price print(fruit, stock, unit_price, value) ''' ''' #Add up the value of the entire inventory. First, initialize a counter. inventory = { "pear": 33, "apple": 27, "orange": 38, "lemon": 26, } price = { "pear": 2, "apple": 1, "orange": 4, "lemon": 3, } # initialize a counter total_value = 0 for fruit in inventory: stock = inventory[fruit] unit_price = price[fruit] value = stock * unit_price #LINE 19 total_value += value #LINE 20 #print(fruit, stock, unit_price, value) #print("Total value:", total_value) #sell a dozen lemons. gems = 62 inventory["lemon"] -= 12 gems += 12 * price["lemon"] print("Gems:", gems) #The total_value variable will store the total value of the entire inventory. #We start this counter at zero before running the loop to add values to it. #The value variable plays a different role: it changes each time through the #loop to store the value of all of the current fruit type. #Each time through the loop, line 19 updates value to compute the #value of the entire supply of the current fruit type. #Line 20 adds this value to the total_value counter. #When the loop finishes, total_value contains the total value of all the #different types of fruit in the inventory. ''' ''' # There are 3 art puzzles, 7 sports puzzles, and 5 nature puzzles in the toy chest. #Set puzzles to store the number of puzzles of each type. toy_chest = { "art": 3, "sports": 7, "nature": 5, } size = { "art": 1000, "sports": 250, "nature": 500, } total_pieces = 0 for puzzle_type in toy_chest: # set number of puzzles puzzles = toy_chest[puzzle_type] #LINE 14 #print(puzzle_type, puzzles) #The toy_chest dictionary stores the number of puzzles of each type. #Line 14 updates the puzzles variable to store this value for each key. #The size dictionary gives the number of pieces for each type of puzzle. #Set pieces to store this value inside the loop. # set number of pieces pieces = size[puzzle_type] #LINE 15 print(puzzle_type, puzzles, pieces) #The size dictionary stores the number of pieces in each each type of puzzle. #Line 15 updates the pieces variable to store this value for each key. #Update total_pieces to count the total number of puzzle pieces in the toy chest. # update total total_pieces += puzzles * pieces print("Total pieces:", total_pieces) #For each type of puzzle, puzzles stores the number of puzzles, and pieces #stores the number of pieces. Multiplying gives the total number of pieces. '''
Editor Settings
Theme
Key bindings
Full width
Lines