LoginSignup
0
0

[Python]for文のループカウンタ

Posted at

結論

forループでループカウンタを変更しても、次の繰り返しには影響しない。
ループカウンタを変更するループ文を書くにはwhileを使う。

説明

for文の中でi(ループカウンタ)を変更するコードを書く。

for i in range(5):
    print(i)
    if i==1: i+=2

i==1の時にi+=2しているため、出力は0,1,4を期待するが、

0
1
2
3
4

となる。
iは同じ変数を使用しているのではなく、繰り返し時にrange(5)=[0,1,2,3,4]から取得しなおしているため、ループ内で変更しても次の繰り返しには影響しない。

ループ内でカウンタを変更するコードを書くには、forではなくwhileを使用する。

i = 0
while i < 5:
    print(i)
    if i == 1: i+=2
    i+=1
0
1
4
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