Basic Python Statements, cont.

<Part 1<

Printing

Printing in Python is extremely simple. Using print writes the output to the C stdout stream and normally goes to the console unless you redirect it to another file.

Printing, by default, adds a space between items separated by commas and adds a linefeed at the end of the output stream. To suppress the linefeed, just add a comma at the end of the print statement:

print lumberjack, spam, eggs,

To suppress the space between elements, just concatenate them when printing:

print "a" + "b"

if Tests

The if statement works the same as other languages. The only difference is the else/if as shown below:

if <test1>: # if test
<statements1> # associated block
elif <test2>: # optional elif's
<statements2>
else: # optional else
<statements3>

Unlike C, Pascal, and other languages, there isn't a switch or case statement in Python. You can get the same functionality by using if/elif tests, searching lists, or indexing dictionaries. Since lists and dictionaries are built at runtime, they can be more flexible. Here's an equivalent switch statement using a dictionary:

>>> choice = 'ham'
>>> print {'spam': 1.25, # a dictionary-based 'switch'
... 'ham': 1.99, #use has_key() test for default case
... 'eggs': 0.99,
... 'bacon': 1.10}[choice]
1.99

while Loops

The Python while statement is, again, similar to other languages. Here's the main format:

while <test>: # loop test
<statements1> # loop body
else: # optional else
<statements2> # run if didn't exit loop with break

break and continue work the exact same as in C. The equivalent of C's empty statement (a semicolon) is the pass statement, and Python includes an else statement for use w/ breaks. Here's a full-blown while loop:

while <test>:
<statements>
if <test>: break # exit loop now, skip else
if <test>: continue # go to top of loop now
else:
<statements> # if we didn't hit a 'break'

>Part 3>