Python Loop

Last modified 4 years ago / Edit on Github
Danger icon
The last modifications of this post were around 4 years ago, some information may be outdated!

for

for i in range(3):
print(i)
1
2
3
for i in range(3):
print(i)
else:
print('no left')
0
1
2
no left

Skip some step

# don't contain 5 (way 1)
for i in [x for x in range(10) if x != 5]:
print i
# don't contain 5 (way 2)
for i in list(range(5)) + list(range(6, 10)):
print i
# next (skip 5)
xr = iter(range(10))
for i in xr:
print(i)
if i == 4: next(xr)
# continue (skip 5)
for i in range(10):
if i == 5: continue
print(i)

while

i = 1
while i < 4:
print(i)
i += 1
1
2
3

You can also use next and continue like in the case of for but with caution!

break

for i in range(6):
print(i)
if i==2: break
0
1
2
i = 1
while i < 6:
print(i)
if i==3: break
i += 1
1
2
3

💬 Comments

Support Thi Support Thi