Python Loops

while statement

while condition:
        statements for condition true
nLayer = 5
i = 1
while i <= nLayer:
	print(i)
	i = i + 1
Output
1
2
3
4
5

range() method

loops through a block of code for a specified number of times.

range(5) loops from 0 to 4 ( 0, 1, 2, 3, 4)

range(1,4) loops from 1 to 3 (1, 2, 3)

range(1, 10, 2) loops in increment of 2 from 1 to 9 (1, 3, 5, 7, 9)

for statement

for x in collection/sequence:
        statements for x is found in collection
for x in range(6):
	print(x)

starts from 0, increments by 1 and ends after specified number of times.

Output
0
1
2
3
4
5

break, continue and else statements in Loops

break

breaks out of the innermost enclosing loop.

continue

continues with the next iteration of the loop.

else

executed after loop completes.

for x in range(6):
	print(x)
else:
	print("Loop Completed")
Output
0
1
2
3
4
5
Loop Completed