0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python] range()の使い方

Posted at

Pythonにおいて、for文で***range()***を使用したので、使い方をまとめておく。

range()の使い方

***range()***は、引数で指定された条件に沿った数値リストを持つ、range型のオブジェクトが作成される。***range()***の書式は以下のようになる。

# 書き方
range(<開始値>,<終了値>,<変化量>)

# 例
data = range(3,15,3)
print(list(data))     # [3, 6, 9, 12]

***range()***の引数の開始値と変化量は省略することができ、この場合は開始値 = 0変化量 = 1として実行される。
また、rangeオブジェクトを表示する際は、直接print()の引数に指定しても表示されず、list型のオブジェクトを作成して表示させる必要がある。

 for文での使用

***range()***を使用してfor文を記述すると以下のようになる。

# 例:3, 6, 9, 12を順番に表示する
for i in range(3,15,3):
    print(i)

# 例:apple,grape,orangeを順に表示する
fruits = ['apple','grape','orange']
for name in fruits:
    print(name)
0
2
1

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?