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
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Control Statements > Loops - Pg. 104

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 state- ments 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. STATEMENT Loop with Final Clause This form of loop statement adds an else clause whose statements are executed after the expression evaluates to false. while expression: statements1 else:xs statements2 There are two simple statements that are associated with both loops and iterations (the subject of the next section): continue and break . STATEMENT Loop Interruption Occasionally it is useful to interrupt the execution of a loop's statements. The continue statement causes execution of the loop to return to the test. The break state- ment interrupts the entire loop's execution, causing the program to continue with the statement following the while . 104 | Chapter 4:Control Statements