Pythonで整数が順番に並んだタプルを返す/range関数の使い方

aged IT

range関数を使うと、指定した範囲の順番に並んだ整数のタプルを取得することができます。

スポンサーリンク

range関数

#python
i = range(1,5)
range関数を使うには、rangeの後に開始値終了値を指定します。
この例では開始値が1終了値が5、結果1から4までの整数が並んだタプルを取得しています。終了値は含まれません。
range 1
そのままprintするとそのまま出力されますが、
range 2
インデクスを付ければ、各値を取り出すことが可能です。
rangeの各値は変更不可です。

for文と組み合わせる

#python
for i in range(1,5):
    print(i)
for文のイテラブルにrange関数を使うことで、比較的シンプルに数字で繰り返し回数を指定することができます。
range 3
実行結果です。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny