While

The While statement:

The flow of execution for a while statement:

  • Determine whether the condition is true or false.
  • If false, exit the while statement and continue execution at the next statement.
  • If the condition is true, run the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

Syntax:

while boolean expression:
statement1
statement2
..
statement3

The body of the loop should change the value of one or more variables so that the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

Example

i=1
while i<=4:
print(i)
i=i+1
Output:
1
2
3
4

infinite loop - Wrong

while i<=10
print(i)

References

  • Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
  • Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
  • John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
  • Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
  • Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015. 4. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
  • Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley India Edition, 2013.
  • Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.