Python Practice › List Programs › Program 87

Bill per fruit purchased

MediumList Programs · 87 of 100

Write a Python program to calculate the bill for each fruit purchased, from a price list and a quantity list.

Advertisement
Input
prices [["apple", 30], ["mango", 50], ["banana", 20], ["lichi", 50]]; bought [["apple", 2], ["mango", 10]]
Output
Fruit: Apple    Bill: 60
Fruit: Mango    Bill: 500
Total: 560

Approach

  1. Turn the price list into a dict for lookup, then multiply price by quantity.

Solution

Python
prices = dict([["apple", 30], ["mango", 50], ["banana", 20], ["lichi", 50]])bought = [["apple", 2], ["mango", 10]]total = 0for fruit, qty in bought:    bill = prices[fruit] * qty    total += bill    print(f"Fruit: {fruit.capitalize():8} Bill: {bill}")print("Total:", total)
Output
Fruit: Apple    Bill: 60
Fruit: Mango    Bill: 500
Total: 560

Line by line

Line 1

dict() accepts a list of [key, value] pairs.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment