Lesson 4

Setting up our Shopping Cart


Next, we will want to make a function to add things to our cart. The first thing we need to know is what item we should add.

If it’s in the store, we’ll add it to our cart, if it’s not, we’ll tell the user it’s not here.

Now that we have a gist of how the function should flow, let’s code it. On line 18, we will define a function. Add the following code: def addToCart():

Next, we need to ask for user input, using the input() function. On line 19 add the following code: selection=input(“What can I get ya? “)

We need to check whether or not the user has selected something valid, using an if statement. On line 20 add the following code: if(selection in store):

Now we need to copy the item from the store into our dictionary. We can do this simply by using the “=”” operator. Remember we can access dictionary entries with square brackets.

On line 21 add the following code: cart[selection]= store[selection]. Make sure that this line of code is inside of the if statment that was set up on the previous line.

We will want to inform the user that the item was added to their cart. This will be accomplished using a print statement. On line 22, add the following code print(selection + ” added to shopping cart”)