Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Pythonにおけるメンバーシップ演算子と型比較 | Pythonにおける条件文
Pythonにおける条件文

bookPythonにおけるメンバーシップ演算子と型比較

メニューを表示するにはスワイプしてください

Pythonのメンバーシップ演算子は、オブジェクトが文字列、リスト、タプルなどのシーケンス内に存在するかどうかを判定します。in演算子はシーケンスが見つかった場合にTrueを返し、not in演算子は見つからなかった場合にTrueを返します。

12345678
# Define a string containing all the vowels vowels = "aeiou" # Check if the character 'n' is present in the `vowels` string print('n' in vowels) # Check if the character 'a' is not present in the `vowels` string print('a' not in vowels)
copy

メンバーシップの判定に加えて、特定の操作を行う前に変数の型を確認する必要がある場合があります。例えば、数値以外の値で割り算を行うとエラーになります。Pythonでは、型を確認する方法としてisisinstance()の2つがあります。

12345678
# Initial number num = 3.5 # Checking if num is an integer using `is` operator print(type(num) is int) # Check if the variable is an integer using the 'isinstance' function print(isinstance(num, int)) # The second approach
copy

どちらの方法も False を返します。なぜなら 3.5float ではなく int だからです。is 演算子は正確な型一致を確認し、isinstance() は複数の型や継承も確認できます。

question mark

Python において in 演算子は何をしますか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  5
some-alt