Python - Statement while Loops

General Format

The while statement consists of

  • a header line with a test expression,
  • a body of one or more normally indented statements, and
  • an optional else part that is executed if control exits the loop without a break statement.

Python keeps evaluating the test at the top and executing the statements nested in the loop body until the test returns a false value:

while test:                     # Loop test 
    statements                  # Loop body 
else:                           # Optional else 
    statements                  # Run if didn't exit loop with break 

The following code outputs the message until you press control c.

while True: 
   print('Type Ctrl-C to stop me!') 

Related Topics

Example