Statements
Now that we know how Python uses it's fundamental data types, let's talk about how to use them. Python is nominally a procedure-based language but as we'll see later, it also functions as an object-oriented language. As a matter of fact, it's similar to C++ in this aspect; you can use it as either a procedural or OO language or combine them as necessary.
The following is a listing of Python statements, borrowed from O'Reilly's Learning Python. It’s not all-inclusive but it gives you an idea of some of the features Python has.
Statement Role Examples Assignment Creating
references new_car = “Porsche” Calls Running functions stdout.write("spam, ham, toast\n") Print Printing objects print 'The Killer', joke Print() Python 3 print
function print(“Have you seen my baseball?”) if/elif/else Selecting
actions if "python" in text: print “yes” For/else Sequence iteration for X in mylist: print X While/else General loops while 1: print 'hello' Pass Empty placeholder while 1: pass Break, Continue Loop jumps while 1: if not line: break Try/except/finally Catching
exceptions try: action() except: print 'action error' Raise Triggering exception
raise locationError Import, From Module
access import sys; from wx import wizard Def, Return Building
functions def f(a, b, c=1, *d): return a+b+c+d[0] Class Building objects
class subclass: staticData = []
Assignment
I’ve already talked about assignment before. To reiterate, assignment is basically putting the target name on the left of an equals sign and the object you're assigning it to on the right. There's only a few things you need to remember:
The final thing to mention
about assignment is that a name can be reassigned to different
objects. Since a name is just a reference to an object and doesn't
have to be declared, you can change it's "value" to
anything. For example:
>>>x = 0 #x is linked to an integer
>>>x = "spam" #now it's a string
>>>x = [1, 2, 3] #now it's a list
Expressions/Calls
Python expressions can be used as statements but since the result won't be saved, expressions are usually used to call functions/methods and for printing values at the interactive prompt.
Here's the typical format:
spam(eggs, ham) #function call using parenthesis
spam.ham(eggs) #method call using dot operator
spam #interactive print
spam < ham and ham != eggs #compound expression
spam < ham < eggs #range test
The range test above lets you perform a Boolean test but in a "normal" fashion; it looks just like a comparison from math class. Again, another handy Python feature that other languages don’t necessarily have.
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.
Now is a good time to mention that Python has 3 streams for input/output (I/O). sys.stdout is the standard output stream; it is normally send to the monitor but can be rerouted to a file or other location. sys.stdin is the standard input stream; it normally receives input from the keyboard but can also take input from a file or other location. sys.stderr is the standard error stream; it only takes errors from the program.
The print statement can be used with either the sys.stdout or sys.stderror streams. This allows you to maximize user effectiveness. For example, you can print all program errors to a log file and normal program output to a printer or another program.
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"
Python 3 replaces the simple
print statement with the print() function. This is to
make it more powerful, such as allowing overloading, yet it requires
very little to change. Instead of using the print statement like I
have throughout the book so far, you simply refer to it as a
function. Here are some examples from the Python
documentation page:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not
the same as print(x, y)!
if Tests
One of the most common control structures you’ll use, and run into in other programs, is the if conditional block. Simply put, you ask a yes or no question; depending on the answer different things happen. For example, you could say, “If the movie selected is ‘The Meaning of Life’, then print ‘Good choice.’ Otherwise, randomly select a movie from the database.”
If you’ve programmed in
other languages, the if statement works the same as other
languages. The only difference is the else/if as shown below:
if item == “magnet”:
kitchen_list = [“fridge”]
elif item == “mirror”: #optional
bathroom_list = [“sink”]
elif item == “shrubbery”: #optional
landscape_list = [“pink flamingo”]
else: #optional
print “No more money to remodel”
Having the elif (else/if) or the else statement isn’t necessary but I like to have an else statement in my blocks. It helps to clarify to me what the alternative is if the if condition isn’t met. Plus, later revisions can remove it if it’s irrelevant.
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
To be honest, I don’t
think about this when I’m programming. It’s not natural
for me yet; I’m still used to using if/elif conditions. Again,
you can create your program using if/elif statements and change them
to dictionaries or lists when you revise it. This can be part of
normal refactoring (rewriting the code to make it easier to manage or
read), part of bug hunting, or to speed it up.
while Loops
while loops are a standard workhorse of many languages. Essentially, the program will continue doing something while a certain condition exists. As soon as that condition is not longer true, the loop stops.
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 with breaks. Here's a full-blown while example
loop:
while <test>:
<statements>
if <test>: break # exit loop now, skip to else statement
if <test>: continue # go to top of loop now
else:
<statements> # if we didn't hit a 'break'
More practical examples will be shown later; I don’t want to overwhelm you and it’s easier to see their use in real programs
for Loops
The for loop is a
sequence iterator for Python. It will work on nearly anything:
strings, lists, tuples, etc. I've talked about for loops
before, and we will see a lot of them in future chapters, so I won't
get into much more detail about them. The main format is below:
for <target> in <object>: # assign object items to target
<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'
From Learning Python:
“When Python runs a for loop, it assigns items in the sequence object to the target, one by one, and executes the loop body for each. The loop body typically uses the assignment target to refer to the current item in the sequence, as though it were a cursor stepping through the sequence. Technically, the for works by repeatedly indexing the sequence object on successively higher indexes (starting at zero), until an index out-of-bounds exception is raised. Because for loops automatically manage sequence indexing behind the scenes, they replace most of the counter style loops you may be used to coding in languages like C.”
In other words, when the for loop starts, it looks at the first item in the list. This item is given a value of 0 (many programming languages start counting at 0, rather than 1). Once the code block is done doing it’s processing, the for loop looks at the second value and gives it a value of 1. Again, the code block does it’s processing and the for loop looks at the next value and gives it a value of 2. This sequence continues until there are no more values in the list. At that point the for loop stops and control proceeds to the next statement in the program.
Related to for loops are range
and counter loops. The range function auto-builds a list of
integers for you. Typically it's used to create indexes for a for
statement but you can use it anywhere.
>>> range(5) #create a list of 5 numbers, starting at 0
[0, 1, 2, 3, 4]
>>>range(2, 5) #start at 2 and end at 5 (remember the index values)
[2, 3, 4]
>>>range(0, 10, 2) #start at 0, end at 10 (index value), with an increment of 2
[0, 2, 4, 6, 8]
As you can see, a single argument gives you a list of integers, starting from 0 and ending at one less than the argument (because of the index). Two arguments give a starting number and the max value while three arguments adds a stepping value, i.e. how many numbers to skip between each value.
pass Statement
The pass statement is
simply a way to tell Python to continue moving, nothing to see here.
Most often, the pass statement is used while initially writing
a program. You may create a reference to a function but haven’t
actually implemented any code for the it yet. However, Python will be
looking for something within that function and will give an exception
and stop when it doesn’t find anything. If you simply put a
pass statement in the function, it will continue on without
stopping.
if variable < 12:
print “Yeah, that’s a big number.”
else: pass
break and continue Statements
Briefly talked about already, these two statements affect the flow control within a loop. When a particular condition is met, the break statement “breaks” out of the loop, effectively ending the loop prematurely (though definitely expected). The continue statement “short circuits” the loop, causing flow control to return to the top of the loop immediately.
I rarely use these statements but they are good to have when needed. The help ensure you don’t get stuck in a loop forever and also ensure that you don’t keep iterating through the loop for no good reason.
try, except, finally and raise Statements
I’ve briefly touched on some of these and will talk about them more in the Exceptions chapter. Briefly, try creates a block that attempts to perform an action. If that action fails, the except block catches any exception that is raised and does something about it. finally performs some last minute actions, regardless of whether an exception was raised or not. The raise statement manually creates an exception.
import and from Statements
These two statements are used to include other Python libraries and modules that you want to use in your program. This helps to keep your program small (you don’t have to put all the code within a single module) and “isolates” modules (you only import what you need). import actually calls the other libraries or modules while from makes the import statement selective; you only import subsections of a module.
def and return Statements
These are used in functions and
methods. Functions are used in procedural-based programming while
methods are used in object-oriented programming. The def
statement defines the function/method. The return statement
returns a value from the function or method, allowing you to assign
the returned value to a variable.
>>> a = 2
>>> b = 5
>>> def math_function():
... return a * b
...
>>> product = math_function()
>>> product
10
Class Statements
These are the building blocks of OOP. Class creates a new object. This object can be anything, whether an abstract data concept or a model of a physical object, e.g. a chair. Each class has individual characteristics unique to that class, including variables and methods. Classes are very powerful and currently “the big thing” in most programming languages. Hence, there are several chapters dedicated to OOP later in the book.