Lesson 3

Printing our Shopping list


We are going to want to print out every item in the list for our user to see. In previous programs, we would have just made it a part of a bigger monstrous program, but now that we understand functions, we can take advantage of them to make our code look and read a lot smoother.

On line 14,, add on the following code: def printItems():

In this function we will want to go through every item in our dictionary, and print it out.

To do this, we’re going to use a for loop in a new way. But first, let’s look at how for loops in python really work.

The key to understanding for loops is the range function, and what it actually does. This function doesn’t count numbers, but rather it makes a list of every number between 0 and 20.

When this loop runs, it takes the word number to represent the first item in that list, then the second item, then the third item, and so on until it gets to the end of the list. So a for loop will only work with a list of things, and go through every item in that list.

Adding Functions


Using this new knowledge, if we wanted to go through every item in a dictionary, all we would need is a list of its individual entries, which we can get by using the function shop.items().

On line 15, add the following code: for item, price in store.items():. Make sure that the line is indented, so that it is inside of our printItems function.

This will loop through every item and price combination in our list of items, setting “item” to the name of the item, and “price” to the numerical price of our item. Now all we need to do is print each item with the corresponding price in our for loop.

On line 16, inside of our for loop, add the following code print(item + “$” + str(price))

In order to test our program, we will need to call for the printItems() function that we defined earlier. On line 18. add the code: printItems() Make sure that it is not indented

When we run our program, the list of items and their prices should appear inside the terminal window. Once we know our code works, remove this line from the program.