!!! Python関連ウェブサイト ,リンク,内容 ,[Python.org|https://www.python.org/],公式サイト ,[Pythonドキュメント|https://docs.python.org/ja/],日本語マニュアル !!! 制御構造 !! 何もしない 何もすることがないときは[pass|https://docs.python.org/ja/3/tutorial/controlflow.html#pass-statements]と書く。 >>> pass !! elif [if文|https://docs.python.org/ja/3/tutorial/controlflow.html#if-statements]におけるelse ifは「elif」と書く。 !! switchは無い Pythonにはswitch文が無く、if文で代用する。 !! 繰り返し ! 無限ループ 無限ループは[while文|https://docs.python.org/ja/3/reference/compound_stmts.html#while]で実現するのが一般的な模様。 import time while True: print(".", end="", flush=True) time.sleep(1) ! range() インデックスを伴ったループには[range()|https://docs.python.org/ja/3/tutorial/controlflow.html#the-range-function]を使う。 for i in range(5): print(i) for i in range(10, 15): print(i) for i in range(0, -10, -2): print(i) ! enumerate() Rubyの[with_index|https://docs.ruby-lang.org/ja/latest/method/Enumerator/i/with_index.html]相当のことは[enumerate()を使って実現|https://docs.python.org/ja/3/tutorial/datastructures.html#tut-loopidioms]する。 array = ["a", "b", "c"] for i, v in enumerate(array): print(i, v) !!! 文字列 !! ""と''の違い 文字列リテラルに使う引用符の["と'に違いはない|https://docs.python.org/ja/3/tutorial/introduction.html#strings]とのこと。 !!文字列に変数の値を埋め込む 文字列リテラルに接頭辞fを付けると変数の値を埋め込めるようになる。 * [2.4.3. フォーマット済み文字列リテラル|https://docs.python.org/ja/3/reference/lexical_analysis.html#f-strings] (Python 言語リファレンス) >>> a = 100 >>> f"value = {a}" 'value = 100' しかし、これはPython 3.6以上でないと使えない。Python 3.5以下では[str.format|https://docs.python.org/ja/3.7/library/stdtypes.html#str.format]を使うしかないみたい。 >>> "value = {0}".format(a) 'value = 100' !!! 算術演算 割り算は常に浮動小数点を返すとのこと。整数除算をしたいときは // 演算子を使う。 >>> 2/3 0.6666666666666666 >>> 2//3 0 剰余には % 、べき乗には ** 演算子を使う。 複素数リテラルをサポートし、数値にjを付けると虚数になる。 >>> 1j ** 2 (-1+0j) * [3.1.1. 数|https://docs.python.org/ja/3/tutorial/introduction.html#numbers] (Python チュートリアル) !!!コメント {{comment}}