Saturday, February 1, 2020

while loop Python

The "while" statement

The "while-statement" is another iteration statement in Python like for-loop. We can execute a piece of code multiple times repeatedly with the help of iteration statements. The "while-loop" keeps executing code inside its body until some applied condition is met. The "while-loop" is especially useful when the number of iterations is not known. For example

Syntax

while [Test condition]:
    [Execute the code]     #identation

The Test Condition can be any expression, that evaluates True or False upon execution. The code to execute must have a proper indentation.

i=5 
# while loop syntax
while i>=0:
  print(i)
  i=i-1

Output:
5
4
3
2
1
0

We can also use a break or a continue inside while the body,

The break statement, like in C, brings control of execution out of the smallest enclosing for or while loop. The continue statement will jump from the current iteration to next within the innermost loop, skipping residual statement in the current loop. Generally, break and continue are used within, if statement with some condition.

def search(num, ls):
  l=len(ls)
  i=0
  while i<l:
    if(num==ls[i]):
      print('found')
      break # break statement
    i=i+1
  if i>=l:
    print('not found')
  
search(7,[12,45,50,1,4])
search(1,[12,45,50,1,4])

Output:
not found
found

Adding else with while

else can also be added with a while. in the end like for statement. It is executed if the test condition is failed.

ls=[23,13,34,112,24,52]
index=0;
while index<len(ls):
  print(ls[index])
  index=index+1
else:
  print('All elements of the list are printed')

Output:
23
13
34
112
24
52
All elements of the list are printed

Try yourself