Python进阶之路 in和not in操作符

版权声明:本教程只限学习交流,不得用于商业用途。 https://blog.csdn.net/weixin_45086637/article/details/91427847

in和not in操作符

利用in和not in操作符,可以确定一个值是否在列表中。像其他操作符一样,in和 not in用在表达式中,连接两个值:一个要在列表中查找的值,以及待查找的列表。这些表达式将求值为布尔值。

>>> 'howdy' in ['hello','hi','howdy','heyas']
True
>>> spam = ['hello','hi','howdy','heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True

例如,下面的程序让用户输入一个宠物名字,然后检查该名字是否在宠物列表中。输入以下代码:

mypets = ['zophie','pooka','fattail']print('Enter a pet name:')
name = input()
if name not in mypets:print('I do not have a pet named ' + name)else:
    print(name + ' is my pet.')

首先,创建一个列表❶,然后通过变量name来保存用户输入的字符串,在通过判断用户输入的字符串是否存在于列表中❷,如果用户输入的字符串不存在于mypets列表中,那么就输出❸。如果用户输入的字符串在列表中存在,那么则输出❹。

猜你喜欢

转载自blog.csdn.net/weixin_45086637/article/details/91427847