0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【公式ドキュメントから学ぶPythonチュートリアル】#2 制御フローツール

Posted at

今回の内容

if 文

x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')
  • switch 文, case 文if ... elif ... elif ...で代用する
  • match 文

for 文

# 文字列の長さを計測:
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))
  • C言語Pascal言語 とは少し違うので注意!
  • 任意のシーケンス型(リストまたは文字列)にわたって反復を行う
  • 反復の順番はシーケンス中に要素が現れる順番
  • コレクションオブジェクトの場合は コレクションオブジェクトのコピーに対して反復処理をする or 新しいコレクションオブジェクトを作成する のどちらかで反復処理を行うのがベスト

range() 関数

for i in range(5):
    print(i) # 出力結果: 0 1 2 3 4

break 文

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(f"{n}{x} * {n//x} と等しい")
            break
  • その break 文 を内包している最も外側にある for 文 or while 文 から抜け出すことができる 

continue 文

for num in range(2, 10):
    if num % 2 == 0:
        print(f"偶数 {num} を見つけた")
        continue
    print(f"奇数 {num} を見つけた")
  • ループの次のイテレーションを実行する
  • 上のプログラムの例では、continue が出たら一番上の for に戻るということ

ループの else 節

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, '', x, '*', n//x, 'と等しい')
            break
    else:
        # 因数が見つからないとループは最後まで実行される
        print(n, 'は素数です')
  • for 文: breakが発生しなかった場合に実行される
  • while 文: ループ条件が偽となった後に実行される
  • どちらのループでも、ループがbreak または returnで終了した場合、else 節の実行はスキップされる
  • try 文

pass 文

while True:
    pass  # キーボード割り込み(Ctrl+C)のためのビジーウェイト
  • pass 文 は何もしない。プログラム上何の動作もする必要がないときに使われる
  • 例1:最小クラスの作成のときに使用
  • 例2:新しいコードを書いているときの関数や条件文の仮置きの本体として使用。こうすることで、より抽象的なレベルで考えることができる

補足

  • 記事中のプログラムは、全てPython公式チュートリアルからコピーさせていただきました
  • 公式チュートリアル後半の 関数定義 については、#3 で投稿予定です
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?