Thi's avatar
HomeAboutNotesBlogTopicsToolsReading
About|My sketches |Cooking |Cafe icon Support Thi
💌 [email protected]

Python Loop

Anh-Thi Dinh
Python
Left aside

for

Skip some step

while

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

break

â—†forâ—‹Skip some stepâ—†whileâ—†break
About|My sketches |Cooking |Cafe icon Support Thi
💌 [email protected]
1for i in range(3):
2    print(i)
11
22
33
1for i in range(3):
2    print(i)
3else:
4    print('no left')
10
21
32
4no left
1# don't contain 5 (way 1)
2for i in [x for x in range(10) if x != 5]:
3    print i
1# don't contain 5 (way 2)
2for i in list(range(5)) + list(range(6, 10)):
3    print i
1# next (skip 5)
2xr = iter(range(10))
3for i in xr:
4    print(i)
5    if i == 4: next(xr)
1# continue (skip 5)
2for i in range(10):
3    if i == 5: continue
4    print(i)
1i = 1
2while i < 4:
3    print(i)
4    i += 1
11
22
33
1for i in range(6):
2    print(i)
3    if i==2: break
10
21
32
1i = 1
2while i < 6:
3    print(i)
4    if i==3: break
5    i += 1
11
22
33