ブール値、特にブール値を返す式で興味深いのは、決定を下し、ブール値に応じて異なる道を進むことができるということです。True
またはFalse
値。
にPython私たちはを使用してそうしますif
ステートメント:
condition = True
if condition == True:
# do something
条件テストが解決したときTrue
、上記の場合のように、そのブロックが実行されます。
ブロックとは何ですか?ブロックとは、右側に1レベル(通常は4スペース)インデントされている部分です。
condition = True
if condition == True:
print(“The condition”)
print(“was true”)
ブロックは、1行または複数行で形成でき、前のインデントレベルに戻ると終了します。
condition = True
if condition == True:
print(“The condition”)
print(“was true”)
print(“Outside of the if”)
と組み合わせてif
あなたは持つことができますelse
ブロック、条件テストの場合に実行されますif
結果False
:
condition = True
if condition == True:
print(“The condition”)
print(“was True”)
else:
print(“The condition”)
print(“was False”)
そして、あなたは異なるリンクを持つことができますif
でチェックelif
、前のチェックがだった場合に実行されますFalse
:
condition = True
name = "Roger"
if condition == True:
print(“The condition”)
print(“was True”)
elif name == “Roger”:
print(“Hello Roger”)
else:
print(“The condition”)
print(“was False”)
この場合の2番目のブロックは、次の場合に実行されます。condition
ですFalse
、 そしてそのname
変数値は「ロジャー」です。
でif
あなたが1つだけを持つことができるステートメントif
そしてelse
チェックしますが、複数のシリーズelif
チェック:
condition = True
name = "Roger"
if condition == True:
print(“The condition”)
print(“was True”)
elif name == “Roger”:
print(“Hello Roger”)
elif name == “Syd”:
print(“Hello Syd”)
elif name == “Flavio”:
print(“Hello Flavio”)
else:
print(“The condition”)
print(“was False”)
if
そしてelse
インライン形式で使用することもできます。これにより、条件に基づいて値などを返すことができます。
例:
a = 2
result = 2 if a == 0 else 3
print(result) # 3
その他のPythonチュートリアル:
- Pythonの紹介
- macOSへのPython3のインストール
- Pythonプログラムの実行
- Python2とPython3
- Pythonでの作業の基本
- Pythonデータ型
- Python演算子
- Python文字列
- Pythonブール値
- Python番号
- Python、入力の受け入れ
- Python制御ステートメント
- Pythonリスト
- Pythonタプル
- Pythonセット
- Python辞書
- Python関数
- Pythonオブジェクト
- Pythonループ
- Pythonモジュール
- Pythonクラス
- Python標準ライブラリ
- Pythonのデバッグ
- Python変数スコープ
- Python、コマンドラインから引数を受け入れる
- Python再帰
- Pythonの入れ子関数
- PythonLambda関数
- Pythonクロージャ
- Python仮想環境
- Pythonを使用してGoProをリモートWebカメラとして使用する
- Python、文字列からリストを作成する方法
- Pythonデコレータ
- PythonDocstrings
- Pythonのイントロスペクション
- Pythonアノテーション
- Python、ディレクトリ内のファイルとフォルダを一覧表示する方法
- Python、数値が奇数か偶数かを確認する方法
- Python、ファイルの詳細を取得する方法
- Python、ファイルまたはディレクトリが存在するかどうかを確認する方法
- Pythonの例外
- Python、ディレクトリの作成方法
- Python、空のファイルを作成する方法
- Python、 `with`ステートメント
- Python、ネットワークリクエストを作成する
- Python、 `pip`を使用してサードパーティパッケージをインストールする
- Python、ファイルの内容を読む