Python中的if not in语句

Python中的if not in语句

Python中的if not in语句

在Python编程语言中,if not in语句是用来判断某个元素是否不包含在某个容器中的条件语句。通常情况下,我们可以使用if not in语句来检查某个元素是否不在列表、元组、字典或字符串中。在本文中,我们将详细介绍if not in语句的用法并给出一些实例代码。

列表中的if not in

首先,让我们看一个简单的示例,检查列表中是否不包含某个元素:

fruits = ['apple', 'banana', 'orange', 'pear']

if 'grape' not in fruits:
    print("Grape is not in the list")
else:
    print("Grape is in the list")

运行结果:

Grape is not in the list

在这个示例中,我们首先定义了一个水果列表fruits,然后使用if not in语句检查'grape'是否不在fruits列表中。因为'grape'并没有包含在fruits列表中,所以程序会输出Grape is not in the list

元组中的if not in

类似地,我们也可以使用if not in语句来检查元组中是否不包含某个元素:

colors = ('red', 'green', 'blue')

if 'yellow' not in colors:
    print("Yellow is not in the tuple")
else:
    print("Yellow is in the tuple")

运行结果:

Yellow is not in the tuple

在这个示例中,我们定义了一个颜色元组colors,然后使用if not in语句检查'yellow'是否不在colors元组中。由于'yellow'并没有包含在colors元组中,所以程序会输出Yellow is not in the tuple

字典中的if not in

除了列表和元组,我们也可以使用if not in语句来检查字典中是否不包含某个键值:

person = {'name': 'Alice', 'age': 30, 'gender': 'female'}

if 'height' not in person:
    print("Height is not in the dictionary")
else:
    print("Height is in the dictionary")

运行结果:

Height is not in the dictionary

在这个示例中,我们定义了一个人员字典person,然后使用if not in语句检查'height'是否不在person字典中。由于'height'并没有作为键包含在person字典中,所以程序会输出Height is not in the dictionary

字符串中的if not in

最后,我们也可以使用if not in语句来检查字符串中是否不包含某个子串:

sentence = "Hello, world!"

if 'Python' not in sentence:
    print("Python is not in the string")
else:
    print("Python is in the string")

运行结果:

Python is not in the string

在这个示例中,我们定义了一个字符串sentence,然后使用if not in语句检查'Python'是否不在sentence字符串中。由于'Python'并没有包含在sentence字符串中,所以程序会输出Python is not in the string

总的来说,if not in语句是一个很方便的Python语句,用于判断某个元素是否不在容器中。通过灵活运用if not in语句,我们可以简洁明了地编写出更加健壮的Python代码。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程