Saturday, February 9, 2019

While loops in Python

We use while loop to execute a bunch of statements repeatedly as long as a condition is true. The loop stops as soon as the condition becomes false.

Example:

To print 1 to 10 using while loop we can use the following code.

i = 1
while i <= 10:
    print(i)
    i = i + 1


The break statement:

The break statement is useful to stop the while loop in the middle of its iteration.

Example:

The following code will print 1, 2


i = 0
while i <= 5:
    i = i + 1
    if i == 3:
        break
    print(i)


The continue statement:

The continue statement is used to skip the current iteration of a while loop and move to the next iteration.

Example:

The following code will skip 3 print 1, 2, 4, 5, 6

i = 0
while i <= 5:
    i = i + 1
    if i == 3:
        continue
    print(i)


Using else with while loop:

Python lets us use an else block with while loops. The else block is executed after the while loop finishes all the iteration. The else block won't be executed if the loop exits abruptly through a break statement.

i = 1
while i < 6:
    print(i)

    i += 1
else:
    print('Tasks to do after the loop finishes')

No comments: