"while" Statement for Execution Loop

This section provides a quick introduction of 'while' statement, which executes a block of sub-statements repeatedly while the given condition is valid.

What Is "while" Statement? A "while" statement is a compound statement that executes a block of sub-statements repeatedly while the given condition is valid.

A "while" statements must have a "while" clause followed by an optional "else" clause:

while condition:
  sub-statement
  sub-statement
  ...
else:
  sub-statement
  sub-statement
  ...

Two special statements can be used the sub-statement block:

Here is a Python sample code, while_test.py, that shows you how to use "while" statements.

#  while_test.py
#- Copyright 2011 (c) HerongYang.com. All Rights Reserved.
#

upperLimit = 20
i = 3
while i<upperLimit:
   isPrime = True
   j = 2
   while j<=i//2:
      isPrime = i%j > 0
      if not isPrime:
         break
      j = j + 1

   if isPrime:
      print("   "+str(i)+" is a prime number.")
   i = i + 1

print("Reached the upper limit "+str(upperLimit))

If you run this sample code, you should get:

herong> python while_test.py
   3 is a prime number.
   5 is a prime number.
   7 is a prime number.
   11 is a prime number.
   13 is a prime number.
   17 is a prime number.
   19 is a prime number.
Reached the upper limit 20

Notice that we have a "while" statement nested inside another "while" statement. The "break" statement inside the inner "while" statement only breaks the immediate containing "while" statement, not the outer "while" statement.

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

Statements - Execution Units

 What Is Statement

 "pass" Statement - Do Nothing Statement

 Expression Statement - One Expression Only

 "=" Statement - Assignment Statement

 "del" Statement - Delete Statement

 "import" Statement to Load Modules

 "if" Statement for Conditional Execution

"while" Statement for Execution Loop

 "for" Statement for Iterative Execution

 "try" Statement to Catch Execution

 "with" Statement for Context Manager

 "match" Statement for Pattern Match

 Function Statement and Function Call

 Iterators, Generators and List Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB