# 文字列での not in演算子の使用
animal_name = "カンガルー"
print("ウ" not in animal_name)
print("ガ" not in animal_name)
print("ゾウ" not in animal_name)
出力結果:
True
False
True
実用例
not in演算子を実際のプログラミングで活用する際の具体的な例を8つ紹介します。これらの例では、動物をテーマにした親しみやすいコードを通して、not in演算子の多様な使用方法を学べます。データの除外処理、条件に合わない要素の抽出、入力値の妥当性検証など、実践的なプログラミングで使われるパターンを網羅しています。各例では、not in演算子がどのような場面で役立つかを具体的に示し、実際のコードとその実行結果を確認できます。
animal_names = ["シカ", "クマ", "ウサギ", "タヌキ"]
excluded_char = "ウ"
filtered_names = []
for name in animal_names:
if excluded_char not in name:
filtered_names.append(name)
print(f"'{excluded_char}'を含まない動物: {filtered_names}")
animal_info = {"name": "コアラ", "habitat": "オーストラリア"}
required_keys = ["name", "age", "habitat"]
for key in required_keys:
if key not in animal_info:
animal_info[key] = "未設定"
print(f"動物情報: {animal_info}")
all_zoo_animals = ["ライオン", "ゾウ", "キリン", "パンダ", "ペンギン"]
carnivores = ["ライオン", "トラ", "ヒョウ"]
large_animals = ["ゾウ", "キリン", "カバ"]
family_friendly = []
for animal in all_zoo_animals:
if animal not in carnivores and animal not in large_animals:
family_friendly.append(animal)
print(f"家族向けの動物: {family_friendly}")
出力結果:
家族向けの動物: ['パンダ', 'ペンギン']
まとめ
not in演算子は、要素の非存在確認を効率的に行うための重要な機能です。データの除外処理、禁止リストとの照合、入力値の妥当性検証など、幅広い用途で活用できる汎用性の高い演算子です。