検索
ホームページバックエンド開発Python チュートリアルPython で `name == 'Kevin' または 'Jon' または 'Inbar' が常に True と評価されるのはなぜですか?

Why Does `name ==

Or を使用した代入が常に True と評価されるのはなぜですか?

論理演算子を使用して複数の値を比較する場合、Python の動作は直感的な理解から逸脱する可能性があります。たとえば、コードでは:

name = input("Hello. Please enter your name: ")
if name == "Kevin" or "Jon" or "Inbar":
    print("Access granted.")
else:
    print("Access denied.")

Python はこの式を次のように評価するため、権限のないユーザーにもアクセスが許可されます。

if (name == "Kevin") or ("Jon") or ("Inbar"):

この場合、結果はどの名前に対しても True になります。 "Jon" と "Inbar" は独立した論理オペランドとして扱われるためです。

値を複数の値と比較する方法その他

複数の値と正しく比較するには:

  • 複数の == 演算子を使用します:
if name == "Kevin" or name == "Jon" or name == "Inbar":
  • を雇用するコレクション:
if name in {"Kevin", "Jon", "Inbar"}:
  • any() とジェネレーター式を使用します:
if any(name == auth for auth in ["Kevin", "Jon", "Inbar"]):

パフォーマンス比較

の場合可読性と効率性を考慮すると、一般にコレクションを使用することが推奨されます。

import timeit
timeit.timeit('name in {"Kevin", "Jon", "Inbar"}', setup="name='Inbar'")  # Faster
timeit.timeit('any(name == auth for auth in ["Kevin", "Jon", "Inbar"])',
             setup="name='Inbar'")  # Slower

解析動作の証明

組み込みの ast モジュールは、a == b のような式が確認されることを確認します。 or c または d は、

BoolOp(
    op=Or(),
    values=[
        Compare(left=Name(...), ops=[Eq()], comparators=[Name(...)]),
        Name(...),
        Name(...),
        Name(...)])

として解析され、「or」が適用されることを示します。個々の比較と表現。

以上がPython で `name == 'Kevin' または 'Jon' または 'Inbar' が常に True と評価されるのはなぜですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
どのデータ型をPythonアレイに保存できますか?どのデータ型をPythonアレイに保存できますか?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

Pythonアレイに間違ったデータ型の値を保存しようとするとどうなりますか?Pythonアレイに間違ったデータ型の値を保存しようとするとどうなりますか?Apr 27, 2025 am 12:10 AM

heouttemptemptostoreavure ofthewrongdatatypeinapythonarray、yure counteractypeerror.thisduetothearraymodule'sstricttypeeencultionyを使用します

Python Standard Libraryの一部はどれですか:リストまたは配列はどれですか?Python Standard Libraryの一部はどれですか:リストまたは配列はどれですか?Apr 27, 2025 am 12:03 AM

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

スクリプトが間違ったPythonバージョンで実行されるかどうかを確認する必要がありますか?スクリプトが間違ったPythonバージョンで実行されるかどうかを確認する必要がありますか?Apr 27, 2025 am 12:01 AM

theScriptisrunningwithwrongthonversionduetorectRectDefaultEntertersettings.tofixthis:1)CheckthedededefaultHaulthonsionsingpython - versionorpython3-- version.2)usevirtualenvironmentsbycreatingonewiththon3.9-mvenvmyenv、andverixe

Pythonアレイで実行できる一般的な操作は何ですか?Pythonアレイで実行できる一般的な操作は何ですか?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

一般的に使用されているnumpy配列はどのようなアプリケーションにありますか?一般的に使用されているnumpy配列はどのようなアプリケーションにありますか?Apr 26, 2025 am 12:13 AM

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

Pythonのリスト上の配列を使用するのはいつですか?Pythonのリスト上の配列を使用するのはいつですか?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

すべてのリスト操作は配列でサポートされていますか?なぜまたはなぜですか?すべてのリスト操作は配列でサポートされていますか?なぜまたはなぜですか?Apr 26, 2025 am 12:05 AM

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい