CHAPTER 1
■
LANGUAGE
AND SYNTAX
14
Once again, very straightforward in terms of printing values of variables. Simply place the variable
within a print statement. We can also use this technique in order to append the values of variables to a
line of text. In order to do so, just place the concatenation operator (+) in between the String of text
which you would like to append to, and the variable you’d like to append.
Listing 1-20.
>>> print 'I like programming in Java, but ' + my_value
I like programming in Java, but I love programming in Jython
This
is great and all, but really not useful if you’d like to properly format your text or work with
int
values. After all, the Python parser is treating the (+) operator as a concatenation operator in this
case...not as an addition operator. Python bases the result of the (+) operator on the type of the first
operand. If you try to append a numeric value to a String you will end up with an error.
Listing 1-21.
>>> z = 10
>>> print 'I am a fan of the number: ' + z
Traceback (most recent call last):
File "
", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects
As you can see from this example, Python does not like this trick very much. So in order to perform
this task correctly we will need to use some of the aforementioned Python formatting options. This is
easy and powerful to do, and it allows one to place any content or value into a print statement. Before
you see an example, let’s take a look at some of the formatting operators and how to choose the one that
you need.
•
%s - String
•
%d - Decimal
•
%f - Float
If you wish to include the contents of a variable or the result of an expression in your print
statement, you’ll use the following syntax:
Listing 1-22.
print 'String of text goes here %d %s %f' % (decimalValue, stringValue, floatValue)
In the pseudocode above (if we can really have pseudocode for print statements), we wish to print
the string of text, which is contained within the single quotes, but also have the values of the variables
contained where the formatting operators are located. Each of the formatting operators, which are
included in the string of text, will be replaced with the corresponding values from those variables at the
end of the print statement. The % symbol between the line of text and the list of variables tells Python
that it should expect the variables to follow, and that the value of these variables should be placed within
the string of text in their corresponding positions.
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
15
Listing 1-23.
>>> string_value = 'hello world'
>>> float_value = 3.998
>>> decimal_value = 5
>>> print 'Here is a test of the print statement using the values: %d, %s, and %f' %
(decimal_value, string_value, float_value)
Here is a test of the print statement using the values: 5,
hello world, and 3.998000
As you can see this is quite easy to use and very flexible. The next example shows that we also have
the option of using expressions as opposed to variables within our statement.
Listing 1-24.
>>> x = 1
>>> y = 2
>>> print 'The value of x + y is: %d' % (x + y)
The value of x + y is: 3
The formatting operator that is used determines how the output looks, it does not matter what type
of input is passed to the operator. For instance, we could pass an integer or float to %s and it would print
just fine, but it will in effect be turned into a string in its exact format. If we pass an integer or float to %d
or %f, it will be formatted properly to represent a decimal or float respectively. Take a look at the
following example to see the output for each of the different formatting operators.
Listing 1-25.
>>> x = 2.3456
>>> print '%s' % x
2.3456
>>> print '%d' % x
2
>>> print '%f' % x
2.345600
Another useful feature of the print statement is that it can be used for debugging purposes. If we
simply need to find out the value of a variable during processing then it is easy to display using the
print
statement. Using this technique can often really assist in debugging and writing your code.
try-except-finally
The
try-except-finally is the supported method for performing error handling within a Python
application. The idea is that we try to run a piece of code and if it fails then it
is caught and the error is
handled in a proper fashion. We all know that if someone is using a program that displays an ugly long
error message, it is not usually appreciated. Using the
try-except-finally statement to properly catch and
handle our errors can mitigate an ugly program dump.
This approach is the same concept that is used within many languages, including Java. There are a
number of defined
error types within the Python programming language and we can leverage these error
types in order to facilitate the
try-except-finally process. When one of the
defined error types is caught,
then a suite of code can be coded for handling the error, or can simply be logged, ignored, and so on.
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
16
The main idea is to avoid those ugly error messages and handle them neatly by displaying a formatted
error message or performing another process.
Listing 1-26.
>>> # Suppose we've calculated a value and assigned it to x
>>> x
8.97
>>> y = 0
>>> try:
... print 'The rocket trajectory is: %f' % (x/y)
... except:
... print 'Houston, we have a problem.
...
Houston, we have a problem.
If there is an exception that is caught within the block of code and we need a way to perform some
cleanup tasks, we would place
the cleanup code within the finally clause of the block. All code within the
finally clause is always invoked before the exception is raised. The details of this topic can be read about
more in Chapter 7. In the next section, we’ll take a look at the raise statement, which we can use to raise
exceptions at any point in our program.
raise Statement
As mentioned in the previous section, the
raise statement is used to throw or “raise” an exception in
Python. We know that a
try-except clause is needed if Python
decides to raise an exception, but what if
you’d like to raise an exception of your own? You can place a
raise statement anywhere that you wish to
raise a specified exception. There are a number of defined exceptions within the language which can be
raised. For instance, NameError is raised when a specific piece of code is undefined or has no name. For
a complete list of exceptions in Python, please visit Chapter 7.
Listing 1-27.
>>> raise NameError
Traceback (most recent call last):
File "
", line 1, in
NameError
If you wish to specify your own message within a raise then you can do so by raising a generic
Exception, and then specifying your message on the statement as follows.
Listing 1-28.
>>> raise Exception('Custom Exception')
Traceback (most recent call last):
File "", line 1, in
Exception: Custom Exception
www.it-ebooks.info