
上QQ阅读APP看书,第一时间看更新
6-10 in和not in表达式
主要是用于判断一个对象是否属于另一个对象,对象可以是字符串(string)、列表(list)、元组(Tuple) (第8章介绍)、字典(Dict) (第9章介绍)。它的语法格式如下:
boolean_value = obj1 in obj2 # 对象obj1在对象obj2内会传回True boolean_value = obj1 not in obj2# 对象obj1不在对象obj2内会传回True
程序实例ch6_42.py:请输入字符,这个程序会判断字符是否在字符串内。

执行结果

其实这个功能一般更常见是用在侦测某个元素是否存在列表中,如果不存在,则将它加入列表内,可参考下列实例。
程序实例ch6_43.py:这个程序基本上会要求输入一个水果,如果列表内目前没有这个水果,就将输入的水果加入列表内。

执行结果
