Back to: Python Programming
0
Membership Operators are used to test whether a value or variable is found in a sequence (string, list, tuple, set, or dictionary). The operators are either 1. In or 2. Not in.
Example:
I’m going to create a “secret” word – say APPLE. Let’s make a game where the user has to guess a letter. After the user inputs a letter, we want to check to see if the letter selected is found in the word. We need a Boolean TRUE if it is and FALSE if it’s not:
word = "APPLE"
letter = input("Guess a letter in the secret word: ")
if letter in word:
print(f"There is a {letter}")
else:
print(f"{letter} was not found")
Conversely, we can use the not in operator:
word = "APPLE"
letter = input("Guess a letter in the secret word: ")
if letter not in word:
print(f"{letter} was not found")
else:
print(f"There is a {letter}")
Using a set:
students = {"Spongebob", "Patrick", "Sandy"}
student = input("Enter the name of a student: ")
if student in students:
print(f"{student} is in this class")
else:
print(f"{student} is NOT in this class")
Using a dictionary of student grades:
grades = {
"Sandy": 'A',
"Squidward": 'B',
"Spongebob": 'C',
"Patrick": 'D'
}
student = input("Enter the name of a student: ")
if student in grades:
print(f"{student}'s grade is {grades[student]}.")
else:
print(f"{student} is not in the dictionary")
Outputs:
Enter the name of a student: Sandy
Sandy's grade is A.
Using a string:
email = "bobdown@gmail.com"
if "@" in email and "." in email:
print("Valid email")
else:
print("Invalid email")