Loops in Python

Python has two kinds of loops

The ‘for loop’

Using for loop we can iterate through the items present in any iterable sequence.

Example

  nums = [1,2,3,4]
  for num in nums:
    print(num)

output:

1
2
3
4

To iterate through a sequence of numbers we can use range and xrange functions

Example

# Prints out the numbers 0,1,2,3,4
for x in range(5):
    print(x)

# Prints out 3,4,5
for x in range(3, 6):
    print(x)

# Prints out 3,5,7
for x in range(3, 8, 2):
    print(x)

output:

0
1
2
3
4
3
4
5
3
5
7

The ‘while loop’

While loop keeps on repeatedly executing the block of code till the condition in the while loop is rendered false.

# Prints out 0,1,2,3,4
count = 0
while count < 5:
    print(count)
    count += 1  # This is the same as count = count + 1

output:

0
1
2
3
4

Try

There are statements that help us to have more control over the way loops work.

The break statement

When python comes across break statement when executing a loop, it stops the execution of both the iteration and the loop

# Prints out 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)

output:

0
1
2
3
4
1
3
5
7
9

The continue statement

When python comes across the continue statement when executing a loop, it stops the ongoing iteration and continues executing the loop.

can we use "else" clause in loops?

unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed. If break statement is executed inside for loop then the "else" part is skipped. Note that "else" part is executed even if there is a continue statement.

# Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))

# Prints out 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("this is not printed because for loop is terminated because of break but not due to fail in condition")

output:

0
1
2
3
4
count value reached 5
1
2
3
4