I need to display book name and calculate average weight of book if the book price is more than 800.
here is my current code, appreciate any help. thank you so much in advance!
def calcWeight():
for book in books:
for key,value in book.items():
if key == 'weight':
if value >= 800:
totalWeight += value
avg = totalWeight / 2
print(avg)
books = [{"name": "textbook", "weight": 500, "price": 800},
{"name": "notebook", "weight": 100, "price": 200},
{"name": "storybook", "weight": 700, "price": 1000}]
for book in books:
for key,value in book.items():
if key == 'price':
if value >= 800:
calcWeight()
>Solution :
books = [{"name": "textbook", "weight": 500, "price": 800},
{"name": "notebook", "weight": 100, "price": 200},
{"name": "storybook", "weight": 700, "price": 1000}]
total = 0
length = 0
for book in books:
if book['price'] >= 800:
total += book['weight']
length += 1
average = total / length
print(average)
You don’t need to loop, in a dictionary, though. In here, I’m assuming what you mean here is that you’re getting the average weight of the books if their price is greater than or equal to 800