Datasheet
Chapter 1: A Python Primer
10
Break and Continue
As with C, in Python you can break out of the innermost for or while loop by using the
break statement. Also as with C, you can continue to the next iteration of a loop by using
the
continue statement.
What about switch or case?
Many of you familiar with other programming languages are no doubt wondering
about a decision - tree structure similar to C ’ s switch statement or Pascal ’ s case.
Unfortunately, you won ’ t find it in Python. However, the conditional
if - elif - else
structure, along with other constructs you ’ ll learn about later, make their absence not
such a big deal.
Decision - Making
When writing a program, it is of course critical to be able to evaluate conditions and make decisions.
Having an
if construct is critical for any language, and Python is no exception.
The if Statement
The if statement in Python, as in other languages, evaluates an expression. If the expression is true,
then the code block is executed. Conversely, if it isn ’ t true, then program execution jumps to the end.
Python also supports use of zero or more
elif statements (short for “ else if ” ), and an optional else
statement, which appears at the end if you also have
elif statements, and would be the “ default ”
choice if none of the
if statements were true.
Here ’ s an example:
> > > name = “Jim”
> > > if name == “Jim”:
print “your name is Jim”
elif name == “Joe”:
print “your name is Joe”
else:
print “I have no idea what your name is”
your name is Jim
> > >
c01.indd 10c01.indd 10 6/2/08 12:03:11 PM6/2/08 12:03:11 PM