Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Loops

A loop is a block of statements that gets executed as long as some condition is true. Loops are expressed in Python using while statements.

statement: Loop

The basic form of loop begins with the keyword while and an expression.

while expression:
    statements

If the expression is true, the statements are executed and the expression is evaluated again. As long as the expression is true, the statements are executed repeatedly. Once the expression is false, the statements are skipped, completing the execution of the while statement.

Note that the test may well be false the first time it is evaluated. In that case, the statements of the block won’t get executed at all. If you want some code to execute once the test is false, include an else clause in your loop.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint