Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Adding a Membership Check

00:00 When a customer currently requests an item that you don’t have in your inventory, the code throws an error. In this lesson, you’ll fix this with a membership check.

00:09 I’m going to say, if ware not in inventory,

00:15 and remember that if you do a membership check on a dictionary, it checks for the keys, which is exactly what we want right now. So if ware not in inventory, then again we’re going to have to print a little message that just lets the person know, "Alas! We trade not in ware", is what this f-string says.

00:32 And the ware is going to be whatever they input. So in this case, we’re trying to make it clear that this merchant does not trade in daggers. And only if this first conditional check doesn’t catch, then you want to continue so we’ll turn the previous if statement into an elif.

00:50 And now you have if are not in inventory then you’re going to print that elif. It’s going to check whether there’s more than zero if it isn’t, then it’s going to print out a message that tells the customer that we generally have this in store, but not right now, and else means we have it in inventory and there’s items available.

01:09 We’re going to print out the message that tells the customer about it.

01:13 Okay, let’s give it a spin.

01:17 python shoppe.py and error is gone. Again, we get the information about the available goblets, mead is not at hand, eight roses, and "Alas! We trade not in dagger." No value judgment, but this merchant just doesn’t do daggers.

01:33 Okay, so this is just an example of how you could use membership checks on a dictionary in that case to implement some logic in your program. And this case, it’s like a first off check, sort of a sanity check for the code that even just sees is the product that customers asking for even something that we ever have basically.

01:51 And you don’t need to do anything else, like any sort of expensive computations that you would do underneath that in an e-commerce store. I don’t know, maybe updating the cart or who knows what.

02:01 You never go there. You just end the program by saying, okay, this is not in our inventory. Sorry. Goodbye. Alright! One practical, very outdated Victorian example of how you could use membership checks in Python.

02:16 And one thing that you may have noticed here that I want to look at a little more in the next lesson is you’re using a for loop where you use the in keyword and then you’re also using here, not in.

02:28 In the next lesson, we’ll look at the difference between those two and why it’s important to know that not all in are alike.

Become a Member to join the conversation.