杰瑞科技汇

Python3中if not in怎么用?

Of course! The phrase if not in in Python is a common way to check for the absence of an item in a sequence. It's the logical opposite of the in operator.

Python3中if not in怎么用?-图1
(图片来源网络,侵删)

Let's break it down.

The Short Answer

if not in is used to execute a block of code only if a specified item is not found in a sequence (like a list, string, tuple, or dictionary).

The basic syntax is:

if item not in sequence:
    # code to run if the item is NOT in the sequence

Understanding the in Operator First

To fully grasp not in, it's helpful to understand its counterpart, in.

Python3中if not in怎么用?-图2
(图片来源网络,侵删)
  • in: Checks for membership. It returns True if the item exists in the sequence.
  • not in: Checks for non-membership. It returns True if the item does not exist in the sequence.

Example with in:

fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
    print("Yes, we have bananas!") # This will be printed
if "grape" in fruits:
    print("Yes, we have grapes!") # This will NOT be printed

The if not in Syntax Explained

Now, let's look at if not in. This is simply combining the if statement with the not in operator.

Example 1: Checking a List

This is the most common use case. Let's say you want to add an item to a list only if it's not already there.

shopping_list = ["milk", "bread", "eggs"]
# Try to add "bread" again
new_item = "bread"
if new_item not in shopping_list:
    print(f"'{new_item}' is not on the list. Adding it.")
    shopping_list.append(new_item)
else:
    print(f"'{new_item}' is already on the list. No need to add.")
print(f"Current shopping list: {shopping_list}")
# Output:
# 'bread' is already on the list. No need to add.
# Current shopping list: ['milk', 'bread', 'eggs']
# Now try to add "butter"
new_item = "butter"
if new_item not in shopping_list:
    print(f"'{new_item}' is not on the list. Adding it.")
    shopping_list.append(new_item)
else:
    print(f"'{new_item}' is already on the list. No need to add.")
print(f"Current shopping list: {shopping_list}")
# Output:
# 'butter' is not on the list. Adding it.
# Current shopping list: ['milk', 'bread', 'eggs', 'butter']

Example 2: Checking a String

You can use not in to check if a substring exists within a larger string.

Python3中if not in怎么用?-图3
(图片来源网络,侵删)
username = "john_doe_123"
if " " not in username:
    print("Username is valid: No spaces found.")
else:
    print("Error: Username cannot contain spaces.")
# Output:
# Username is valid: No spaces found.

Example 3: Checking a Tuple

Tuples are immutable lists, but the not in operator works the same way.

week_days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
day_to_check = "Saturday"
if day_to_check not in week_days:
    print(f"'{day_to_check}' is not a weekday.")
else:
    print(f"'{day_to_check}' is a weekday.")
# Output:
# 'Saturday' is not a weekday.

Example 4: Checking a Dictionary Keys

When you use in or not in with a dictionary, it checks for the keys by default.

user = {"name": "Alice", "age": 30, "city": "New York"}
# Check if a key exists
if "country" not in user:
    print("The key 'country' is not in the user dictionary.")
    # You might want to add it
    user["country"] = "USA"
print(user)
# Output:
# The key 'country' is not in the user dictionary.
# {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

Common Pitfalls and Best Practices

a. Case-Sensitivity

String searches are case-sensitive. "Apple" is not the same as "apple".

text = "Python is a great language"
if "python" not in text:
    # This condition is True because 'python' is lowercase
    print("The word 'python' (lowercase) was not found.")
# To make it case-insensitive, convert both to the same case
if "python".lower() not in text.lower():
    print("The word 'python' was not found (case-insensitive check).")
else:
    print("The word 'python' was found (case-insensitive check).")

b. Using if not vs. if not in

This is a very common point of confusion for beginners.

  • if not item: Checks if the item itself is "falsy". An empty string , an empty list [], None, or the number 0 are all considered falsy.
  • if item not in sequence: Checks if the item is absent from the sequence. The item itself can be "truthy" or "falsy".

Example to illustrate the difference:

my_list = []
# --- Case 1: if not my_list ---
# This checks if my_list is empty. It is, so the condition is True.
if not my_list:
    print("Case 1: The list is empty (or 'falsy').") # This will be printed
# --- Case 2: if [] not in my_list ---
# This checks if the empty list [] is an *element* inside my_list.
# my_list is currently empty, so it does not contain [] as an element.
# The condition is also True.
if [] not in my_list:
    print("Case 2: The empty list [] is not an element in my_list.") # This will also be printed
# Now let's add an empty list to my_list
my_list.append([])
print("\nAfter adding an empty list:")
print(f"my_list is now: {my_list}")
# --- Case 1 (re-evaluated) ---
# my_list is no longer empty, so `not my_list` is False.
if not my_list:
    print("Case 1: The list is empty (or 'falsy').") # This will NOT be printed
# --- Case 2 (re-evaluated) ---
# Now my_list IS `[]`, so `[] not in my_list` is False.
if [] not in my_list:
    print("Case 2: The empty list [] is not an element in my_list.") # This will NOT be printed
else:
    print("Case 2: The empty list [] IS an element in my_list.") # This will be printed

Summary

Operator What it Checks Returns True When... Example
in Membership An item is found in a sequence. if "cat" in animals:
not in Non-Membership An item is not found in a sequence. if "dog" not in animals:

Use if not in when your goal is to confirm the absence of something before taking an action. It's a clean, readable, and Pythonic way to handle such checks.

分享:
扫描分享到社交APP
上一篇
下一篇