Shawn's blog Shawn's blog
About Me
  • Category
  • Tag
  • Archive
GitHub (opens new window)

Shawn Jin

I am not a creator of knowledge, I am just a porter of knowledge.
About Me
  • Category
  • Tag
  • Archive
GitHub (opens new window)
  • Python

    • Python import files from different directories
    • Single/Double Star (*/**) Parameters in Python
    • Classmethod in Python
    • Python modify range variable in for loop
  • Git

  • Notes
  • Python
Shawn Jin
2019-12-31

Python modify range variable in for loop

# Python modify range variable in for loop

When I want to done a job like below, I noticed that python doesn't support modify range variable like java or c code.

# It supposed to be infinity loop
for i in range(5):
    print('i:', i)
    i-=1
'''
output:
i: 0
i: 1
i: 2
i: 3
i: 4
'''
1
2
3
4
5
6
7
8
9
10
11
12

The reason it Python doesn't care about the current value of i. It runs like linked list, and using next to iterate and finish the loop. Thus, this method doesn't support by Python. To do something like that, we can use a while loop like below.

i = 0
while (i < 5):
  print('i:',i)
  i+=1
  if (i==2):
    i+=2
'''
output:
i: 0
i: 1
i: 4
'''
1
2
3
4
5
6
7
8
9
10
11
12
#Python
Updated: 2021/09/05, 15:42:35
Classmethod in Python
Force Git Pull and Ignore Local Change

← Classmethod in Python Force Git Pull and Ignore Local Change→

最近更新
01
Python import files from different directories
12-31
02
Classmethod in Python
09-15
03
Single/Double Star (/*) Parameters in Python
09-15
更多文章>
Theme by Vdoing | Copyright © 2019-2021 Shawn Jin | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式