Python 3x Pandas Django

While


while loop is a control flow statement that executes a block of code at least once, and then either repeatedly executes the block, or stops executing it, depending on a given boolean condition at the end of the block.

Syntax

while (condition):
    .....
    condition

Code Snippet

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

Output:

1
2
3
4

Flow Diagram

whileloops

break keyword

It terminates the current loop and resumes execution at the next statement.

In below example, break statement terminates the loop when it reach 5 and it resumes execution at the next print statement.

i = 1
while i < 10:
   print(i)
   if i == 5:
      break
   i += 1
print("While loop completed")

Output:

  1
  2
  3
  4
  5
  While loop completed

While loop with else

else: block is optional, this block executes after finishing the while loop block successfully (without break statement)

Without break
counter = 0

while counter < 3:
    counter = counter + 1
    print("Inside while")
else:
    print("Inside else")

print("Counter value is " + str(counter))

Output

Inside while
Inside while
Inside while
Inside else
Counter value is 3

With break
counter = 0

while counter < 3:
    counter = counter + 1
    print("Inside while")
    break
else:
    print("Inside else")

print("Counter value is " + str(counter))

Output

Inside while
Counter value is 1

continue keyword

It is used to end the current iteration in a while\for loop, and continues to the next iteration.

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

print("While loop completed")

Output:

  1
  2
  3
  4
  6
  7
  8
  9
  10
  While loop completed

In the above example, continue keyword used to end 5th loop in the iteration and continues with the remaining loops.

Pass statement

In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.

i = 0
while i < 5:
   i += 1
   if i == 5:
      pass #nothing happens but you may implement some logic in the future
   print(i)

print("While loop completed")

Output:

1
2
3
4
5
While loop completed

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!