Instagram
youtube
Facebook
Twitter

while loop

  • While loop in python works on the concept of iterating a statement till the conditional statement is True.
  • While loop is preferred over for loop if there is a condition to be checked before iteration occurs.
  • While loop also uses less memory to iterate hence the processing speed or time complexity of the while loop is lesser than that of for loop.

example - 

num = 5
i = 0

while i < num:   #Condition to check before running loop
    print(i)
    i = i + 1

Output- 

0
1
2
3
4
  • In this example, two variables are defined num and I.
  • while i < num statement it is checked whether the variable i is less than num.
  • If the condition is satisfied then loop will keep iterating.