「Pythonの基礎 - 条件分岐」の版間の差分
ナビゲーションに移動
検索に移動
細 (文字列「<source lang="python">」を「<syntaxhighlight lang="python">」に置換) |
細 (文字列「</source>」を「</syntaxhighlight>」に置換) |
||
12行目: | 12行目: | ||
else: | else: | ||
実行コードB | 実行コードB | ||
</ | </syntaxhighlight> | ||
<br> | <br> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
23行目: | 23行目: | ||
# 出力 | # 出力 | ||
I want to eat something! | I want to eat something! | ||
</ | </syntaxhighlight> | ||
<br><br> | <br><br> | ||
40行目: | 40行目: | ||
else: | else: | ||
実行コードC | 実行コードC | ||
</ | </syntaxhighlight> | ||
<br> | <br> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
55行目: | 55行目: | ||
# 出力 | # 出力 | ||
I want to learn how to make iPhone apps. | I want to learn how to make iPhone apps. | ||
</ | </syntaxhighlight> | ||
<br><br> | <br><br> | ||
77行目: | 77行目: | ||
# 出力 | # 出力 | ||
I want to learn how to make iPhone apps. | I want to learn how to make iPhone apps. | ||
</ | </syntaxhighlight> | ||
<br><br> | <br><br> | ||
__FORCETOC__ | __FORCETOC__ | ||
[[カテゴリ:Python]] | [[カテゴリ:Python]] |
2021年11月24日 (水) 18:07時点における最新版
概要
ここでは、Pythonにおけるif文を使用した条件分岐について記載する。
条件式をコロンで終了し、ブロック部分は半角スペース4つ分のインデントで字下げして記述するという特徴がある。
if文とif-else文の条件分岐
条件式Aが成立するなら実行コードAが実行され、成立しないならば実行コードBが実行される。
if 条件式A:
実行コードA
else:
実行コードB
hungry = True
if hungry:
print('I want to eat something!')
else:
print('I am full.')
# 出力
I want to eat something!
elif文を使用した条件分岐
C/C++/C#等ではelse ifだが、Pythonではelifと記述する。
条件式Aが成立すれば実行コードA、成立していなければ条件式Bが検証され成立していれば実行コードB、いずれの条件も成立していなければ実行コードCが実行される。
検証したい条件が更に必要であれば、elif文を必要な分だけ記述する。
Pythonには他のプログラミング言語にあるswitch文が存在しない。Pythonでは、switch文と同じような処理をelif文を使用する。
if 条件式A:
実行コードA
elif 条件式B:
実行コードB
else:
実行コードC
code = "Swift"
if code == "Python":
print('I want to learn Django!')
elif code == "PHP":
print('I want to learn WordPress!')
elif code == "Swift":
print('I want to learn how to make iPhone apps.')
else:
print('I\'m going out for a walk.')
# 出力
I want to learn how to make iPhone apps.
if文の入れ子構造
条件の変数を2つ用意(複数条件)して、if文を入れ子構造で記述することができる。
入れ子のインデントの位置を間違えると、ブロックと認識されないので注意すること。
code = "Swift"
if code == "Python":
print('I want to learn Django!')
else:
if code == "PHP":
print('I want to learn WordPress!')
else:
if code == "Swift":
print('I want to learn how to make iPhone apps.')
else:
print('I\'m going out for a walk.')
# 出力
I want to learn how to make iPhone apps.