How to do it...

  1. Is the programming focused on doing membership tests? An example of this is a collection of valid input values. When the user enters something that's in the collection, their input is valid, otherwise it's invalid.

Simple membership suggests using a set:

        valid_inputs = {"yes", "y", "no", "n"} 
        answer = None 
        while answer not in valid_inputs: 
            answer = input("Continue? [y, n] ").lower() 

A set holds items in no particular order. Once an item is a member, we can't add it again:

      >>> valid_inputs = {"yes", "y", "no", "n"} 
      >>> valid_inputs.add("y") 
      >>> valid_inputs  
      {'no', 'y', 'n', 'yes'} 

We have created a set, valid_inputs, with four distinct string items. We can't add another y to a set which already contains y. The contents ...

Get Modern Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.