# Demo entry 6345785

Mike's shopping list

Submitted by Brendan on Feb 07, 2017 at 23:13
Language: Python 3. Code size: 1.5 kB.

```# Let's have a look at lists

foodprices = [
{ "name": "eggs", "price": 2 },
{ "name": "milk", "price": 4 },
{ "name": "tea", "price": 3 },
{ "name": "pasta", "price": 6 },
{ "name": "chips", "price": 8 }
]

# For a given amount of dollars, for a given amount
# of money to spend, what items can we buy?

print("Welcome to Mike's supermarket! This is what we have for sale: ")

print()

for food in foodprices:
print(food["name"] + " for \$" + str(food["price"]))

print()

money = None

while True:
try:
money = input("How much money would you like to spend? ")

# Turn the string into a integer ( number )
money = int(money)

break
except Exception as err:
print(err)
print("That's not a valid input!")

# Prepare our variables

shoppinglist = [ ]

if money < 0:
print("Can't have a negative value!")
exit(1)

while len(foodprices) > 0:
cheapest = foodprices[0]

for item in foodprices:
if item["price"] < cheapest["price"]:
cheapest = item

if money - cheapest["price"] < 0:
break

money = money - cheapest["price"]
shoppinglist.append(cheapest["name"])
foodprices.remove(cheapest)

print()

print("You were able to buy, " + str(shoppinglist) + " with \$" + str(money) + " left over. ")

print()

input("Press any key to continue...")

# That's it!
```

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.