Python で ifnot 条件を使用する
    
    
            Najwa Riyaz
    2023年10月10日
    
    Python
    Python Condition
    
 
if ステートメントを not 論理演算子と組み合わせて、条件が発生しなかったかどうかを評価します。この記事では、Python で if not の条件を使用する方法について説明します。
これは、この状態を示すコードブロックです。
if not a_condition:
    block_of_code_to_execute_if_condition_is_false
上記の場合、a_condition の結果が False の場合、コード block_of_code_to_execute_if_condition_is_false は正常に実行されます。
Python の真と偽の値
始める前に、次の場合、Python では同等の値が False であることを理解しましょう。
- 0、- 0L、- 0.0などの数値ゼロ値
- 次のような空のシーケンス:
- 空のリスト[]
- 空の辞書{}
- 空の文字列 ''
- 空のタプル
- 空集合
- Noneオブジェクト
 
Python のそうでない場合の条件の例
Python でそうでない場合がどのように利用されているかを理解するのに役立ついくつかの例を次に示します。
ブール値の使用
if not False:
    print("not of False is True.")
if not True:
    print("not of True is False.")
出力:
not of False is True.
数値値の使用
たとえば、0、0L、0.0 などの値は、値 False に関連付けられています。
if not 0:
    print("not of 0 is True.")
if not 1:
    print("not of 1 is False.")
出力:
not of 0 is True.
値のリストの使用法
if not []:
    print("An empty list is false. Not of false =true")
if not [1, 2, 3]:
    print("A non-empty list is true. Not of true =false")
出力:
An empty list is false. Not of false =true
辞書値の使用法
if not {}:
    print("An empty dictionary dict is false. Not of false =true")
if not {"vehicle": "Car", "wheels": "4", "year": 1998}:
    print("A non-empty dictionary dict is true. Not of true =false")
出力:
An empty dictionary dict is false. Not of false =true
値の文字列の使用法
if not "":
    print("An empty string is false. Not of false =true")
if not "a string here":
    print("A non-empty string is true. Not of true =false")
出力:
An empty string is false. Not of false =true
None 値の使用法:
if not None:
    print("None is false. Not of false =true")
出力:
None is false. Not of false =true
値のセットの使用法:
dictvar = {}
print("The empty dict is of type", type(dictvar))
setvar = set(dictvar)
print("The empty set is of type", type(setvar))
if not setvar:
    print("An empty set is false. Not of false =true")
出力:
   The empty dict is of type <class 'dict'>
   The empty set is of type <class 'set'>
   An empty dictionary dict is false. Not of false =true
タプル値の使用
空のタプルは値 False に関連付けられています。
if not ():
    print("1-An empty tuple is false. Not of false =true")
if not tuple():
    print("2-An empty tuple is false. Not of false =true")
出力:
1-An empty tuple is false. Not of false =true
2-An empty tuple is false. Not of false =true
        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe