Pythonブランチステートメントif

概要概要

Pythonでサポートされている一般的なデータロジックの判断条件
等しい:a == b
等しくない:a!= b
未満:a <b
以下:a <= b
より大きい:a> b
以上:a> = b

ifステートメント

a = 66
b = 200
if b > a :
    print("b is greater than a")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
b is greater than a
Process finished with exit code 0

if ... elifステートメント

a = 200
b = 200
if b > a :
    print("b is greater than a")
elif b == a:
    print("b is equal a")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
b is equal a
Process finished with exit code 0

if ... elif ... elseステートメント

a = 200
b = 99
if b > a :
    print("b is greater than a")
elif b == a:
    print("b is equal a")
else:
    print("b is less than a")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
b is less than a
Process finished with exit code 0

Pythonはインデントに依存し、スペースを使用してコード内の範囲を定義します。他のプログラミング言語は通常、この目的のために中括弧を使用します

単一行のifステートメント

実行するステートメントが1つしかない場合は、ifステートメントと同じ行に配置できます。

a = 200
b = 66
if a > b: print("a is greater than b")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
a is greater than b
Process finished with exit code 0

単一行のif ... elseステートメント

実行するステートメントが2つしかない場合(1つはif用、もう1つはelse用)、すべてを同じ行に配置できます。

a = 200
b = 66
print("A") if a > b else print("B")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
A
Process finished with exit code 0

3つの条件を持つ1行のif ... elseステートメント

a = 200
b = 66
print("A") if a > b else print("=") if a == b else print("B")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
A
Process finished with exit code 0

条件を組み合わせたIfステートメント

およびifステートメント

a = 200
b = 66
c = 500
if a > b and c > a:
  print("Both conditions are True")
else:
    print("conditions is not True")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
Both conditions are True
Process finished with exit code 0

またはifステートメント

a = 200
b = 66
c = 500
if a > b or a > c:
  print("At least one of the conditions is True")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
At least one of the conditions is True
Process finished with exit code 0

ネストされたifステートメント

x = 52

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

出力:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
Above ten,
and also above 20!
Process finished with exit code 0

パスステートメント

ifステートメントを空にすることはできませんが、何らかの理由で内容のないifステートメントを作成する場合は、エラーを回避するためにpassステートメントを使用してください。

a = 66
b = 200

if b > a:
  pass

【前のページ】【次のページ】

おすすめ

転載: blog.csdn.net/wzc18743083828/article/details/109789879