【Python】 Python ~ 基本編 / 条件分岐 ~

■ はじめに

if 文などの条件分岐について、学ぶ。

Java や他のプログラムと比較すると、
switch文がないなどかなり違う点がある。

目次

【1】if文
 1)ifのみ
 2)if / elif / else
【2】比較演算子「and / or / not」
【3】三項演算子
【4】in / not in
 1)in / not in
 2)switch文の代替
【5】大小比較
 1)文字列の大小比較
 2)リスト(タプル)の大小比較

【1】if文

「:」が後に必要(忘れがち...)

 1)ifのみ

構文

if 【条件式】:
  【条件が真のときに実行】

number = 16
if number > 15:
    print("とても大きい数字。")

 2)if / elif / else

構文

if 【条件式1】:
  【条件式1が真のときに実行】
elif 【条件式2】:
  【条件式2が真のときに実行】
else:
  【それ以外ときに実行】

例1

file_extension = '.csv'

if file_extension == '.sh':
  print(f"[Shell] file_extension = {file_extension}")
elif file_extension == '.tsv' or file_extension == '.csv':
  print(f"[CSV] file_extension = {file_extension}")
else:
  print("Other")

# [CSV] file_extension = .csv

例2

number = 14
if number > 15:
    print("とても大きい数字")
 # numberが11以上15以下の時、「中くらいの数字」と出力
elif 11 <= number and number >= 15:
    print("中くらいの数字")
else:
    print("小さい数字")

 【2】比較演算子「and / or / not」

+ and 条件式
+ or 条件式
+ not 条件式

【3】三項演算子

いやー、はじめてみた時、何してるか分からなかった...

構文

【結果】 = 【条件Trueの場合】 if (【条件】) else (条件Falseの場合)

例1:Hello world

result = "OK" if is_ok else "NG"

result2 = lambda x: '3未満' if x < 3 else '3以上'

例2:OSによる改行コードの切替
https://www.atsumitakeshi.com/python/py_os_discrim.html

 import os

# Windowだったら「\r\n」、それ以外は「\n」
new_line = "\r\n" if os.name == 'nt' else "\n"

【4】in / not in

in / not in を使えば、指定した値が含まれている(include)かどうか判定可能

1)in / not in

サンプル:文字列中にカンマが含まれているかどうか

def main():
    str = 'aaa,bbb'

    if ("," in str):
        print("カンマはいってる")
    else:
        print("カンマはいってない")

if __name__ == '__main__':
    main()

参考文献
https://www.sejuku.net/blog/15588

2)switch文の代替

* 冒頭でも触れたとおり、switch文がないので
 以下のような書き方をするために、in を使う
~~~~
switch (i) {
  case 0:
  case 1:
     // xxx
}
~~~~

サンプル

value = "Hello"

if value in {"Hello", "World"}:
    print("Hello World!")
else:
    print("Not Hello World...")

参考文献
https://qiita.com/Go-zen-chu/items/9bc7011616759dd2fc93

【5】大小比較

あくまで資格試験の勉強の一環として、、、

https://dk521123.hatenablog.com/entry/2020/11/21/000000

1)文字列の大小比較

print("a" < "b") # True : abc順で
print("A" < "b") # True : 大文字でもabc順
print("ab" < "b") # True : 始めの文字同士で比較
print("aa" < "ab") # True : 始めの文字は同じで二番目の文字で比較
print("a" < "aa") # True : 始めの文字は同じで二番目の文字で比較(左はなかったので)
#print("a" < 0) # TypeError: '<' not supported between instances of 'str' and 'int'

2)リスト(タプル)の大小比較

print(('aa', 'bb', 'cc') < ('aa', 'ca', 'aa')) # True : 'bb' < 'ca' により
print((2, 3, ('aa', 'ab')) < (2, 3, ('abc', 'a'), 5)) # True : 'aa' < 'abc' により

参考文献
https://python.atelierkobato.com/compare/

関連記事

Python ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/08/07/231242
Python 3 エンジニア認定基礎試験
https://dk521123.hatenablog.com/entry/2020/11/21/000000

Python ~ 基本編 ~

繰り返し
https://dk521123.hatenablog.com/entry/2019/08/25/000330
文字列
https://dk521123.hatenablog.com/entry/2019/10/12/075251
コメント文
https://dk521123.hatenablog.com/entry/2019/10/23/212149
関数def (可変長引数 etc)
https://dk521123.hatenablog.com/entry/2019/09/22/000000
global変数
https://dk521123.hatenablog.com/entry/2019/12/12/232749
クラス・継承
https://dk521123.hatenablog.com/entry/2019/08/29/220537
日付・日時
https://dk521123.hatenablog.com/entry/2019/10/14/121909
リスト
https://dk521123.hatenablog.com/entry/2019/10/12/084943
辞書
https://dk521123.hatenablog.com/entry/2019/10/27/100014
タプル・集合
https://dk521123.hatenablog.com/entry/2019/10/26/000000
Enum
https://dk521123.hatenablog.com/entry/2019/11/26/234736
ラムダ lambda
https://dk521123.hatenablog.com/entry/2019/09/23/000000
例外処理
https://dk521123.hatenablog.com/entry/2019/08/03/000000
正規表現
https://dk521123.hatenablog.com/entry/2019/09/01/000000
標準入力 input
https://dk521123.hatenablog.com/entry/2019/08/02/000000
コマンドライン引数
https://dk521123.hatenablog.com/entry/2019/10/11/223651
パッケージ化
https://dk521123.hatenablog.com/entry/2019/09/21/000000
フォルダ・ファイル操作
https://dk521123.hatenablog.com/entry/2019/09/02/000000
ファイル圧縮/解凍
https://dk521123.hatenablog.com/entry/2019/09/03/000000
ファイル読込・書込
https://dk521123.hatenablog.com/entry/2019/10/07/000000
CSV
https://dk521123.hatenablog.com/entry/2019/11/07/214108
YAML
https://dk521123.hatenablog.com/entry/2019/10/16/225401
JSON
https://dk521123.hatenablog.com/entry/2019/10/19/104805
シリアライズ・デシリアライズ
https://dk521123.hatenablog.com/entry/2019/10/06/000000
ジェネリック
https://dk521123.hatenablog.com/entry/2019/12/11/231948
eval, exec
https://dk521123.hatenablog.com/entry/2020/05/15/140053
デコレータ @xxxx
https://dk521123.hatenablog.com/entry/2020/05/19/000000