See All Titles |
![]() ![]() Control StatementsPython implements all the necessary types of control statements that your program might require. The syntax provided by Python's if, for, and while statements should be enough for your needs. Tip
Remember to type a colon at the end of each line where you enter a statement declaration. if/elif/elseThe general syntax for the if/elif/else statement is as follows: 1: if <condition>: 2: <statements> 3: [elif <condition>: 4: <statements>] 5: [elif <condition>: 6: pass] 7: … 8: [else: 9: <statements>] Note that both elif and else clauses are optional. As you can see in lines 3 through 7, it is only necessary to use elif when you need to handle multiple cases. That is exactly how you implement the switch/case statements from other languages. Line 6 introduces you to an empty clause that does nothing. It is called pass. forThe for statement implements loops within a sequence (list). Each element in the sequence assigns its value to variable on its turn. The general syntax is as follows: for <variable> in <sequence>: <statements> [else: <statements>] The else clause is only executed when the for statement isn't executed at all, or after the last loop has been executed. In other words, the else statement is always executed unless the break statement is executed inside the loop. Let's see some examples: >>> for n in [1,2,3,4,5]: … print n, … 1, 2, 3, 4, 5 >>> t = [(1,2),(2,4),(3,6)] >>> for t1, t2 in t: … print t1, t2 … 1 2 2 4 3 6 whileThe while statement implements a loop that executes the statements while the condition returns true. while <condition>: <statements> [else: <statements> The else clause is only executed when the while statement isn't executed at all, or after the last loop has been executed. In other words, the else statement is always executed unless the break statement is executed inside the loop. The following example demonstrates the use of the while statement: >>> x = 5 >>> while x > 0: … print x, … x = x-1 … 5 4 3 2 1 The next example implements an infinite loop because the pass statement does nothing and the condition will always be true. >>> while 1: … pass break/continueNext are two commands that can be used inside for and while types of loop. breakThe break clause exits a loop statement without executing the else clause. >>> for n in [1, 2, 3]: … print n, … if n == 2: … break … else: … print "done" … 1 2 continueThe continue clause skips the rest of the loop block, jumping all the way back to the loop top. >>> x = 5 >>> while x > 0: … x = x - 1 … if x == 3: … continue … print x, … 4 2 1 0
|
Index terms contained in this sectioncontrol statements 2ndelse statement 2nd if/elif/else statement pass statement statements control 2nd else 2nd if/elif/else pass while syntax statements for if/elif/else while statement |
© 2002, O'Reilly & Associates, Inc. |