\

Pythonのin演算子は、リストやタプルなどに特定の要素が含まれているかどうかを確認・判定できます。また、forループの繰り返し処理を行う場合にも使用されます。

in演算子の基本的な使い方

リストで使用する場合

num = [1, 2, 3]
name = ["太郎", "次郎", "三郎"]
print(10 in num)  # 出力結果: False
print("太郎" in name)  # 出力結果: True

文字列で使用する場合

word = "おはようございます。"
print("お" in word)  # 出力結果: True
print("おはよう" in word)  # 出力結果: True
print("あ" in word)  # 出力結果: False

if文 (条件分岐)で使用する場合

in演算子とif文 (条件分岐)を組み合わせることができます。

num = [0, 1, 2]
word = ["木", "火", "風", "雷"]

if 2 in num:
    print("2はリストにあります。")
if "土" in word:
    print("雷はリストにあります。")

辞書変数で使用する場合

alpha= {'A': 'apple', 'B': 'ball', 'c': 'cat', 'D': 'dog'}
print('A' in alpha)  # 出力結果: True
print('apple' in alpha.values())  # 出力結果: True
print(('A','apple') in alpha.items())  # 出力結果: True

以上がPythonのin演算子の基本的な使い方になります。これらの例を参考に、自分のコードに適用してみてください。.

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です