next up previous contents index
Next: top Up: Conditionals and recursion Previous: top   Contents   Index

startsection section 1 0mm-3.5ex plus -1ex minus -.2ex0.7ex plus.2exConditional execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:


if x > 0:
  print "x is positive"

The boolean expression after the if statement is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.

Like other compound statements, the if statement is made up of a header and a block of statements:


HEADER:
  FIRST STATEMENT
  ...
  LAST STATEMENT

The header begins on a new line and ends with a colon (:). The indented statements that follow are called a block. The first unindented statement marks the end of the block. A statement block inside a compound statement is called the body of the statement.

There is no limit on the number of statements that can appear in the body of an if statement, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven't written yet). In that case, you can use the pass statement, which does nothing.


next up previous contents index
Next: top Up: Conditionals and recursion Previous: top   Contents   Index
root 2004-05-05