CHAPTER 1
■
LANGUAGE
AND SYNTAX
11
Listing 1-14. Simple Python Class
>>> class my_object:
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
... def mult(self):
... print self.x * self.y
...
... def add(self):
... print self.x + self.y
...
>>> obj1 = my_object(7, 8)
>>> obj1.mult()
56
>>> obj1.add()
15
In this class example, we define a class named
my_object. The class accepts two parameters,
x and
y.
A class initializer method is named
__init__(), and it is used to initialize any values that may be used in
the class. An initializer also defines what values can be passed to a class in order to create an object. You
can see that each method and function
within the class accepts the self argument. The
self argument is
used to refer to the object itself, this is how the class shares variables and such. The
self keyword is
similar to
this in Java code. The
x and
y variables in the example are named
self.x and
self.y in the
initializer, that means that they will be available for use throughout the entire class. While working with
code within the object, you can refer to these variables as
self.x and
self.y. If you create the object and
assign a name to it such as
obj1, then you can refer to these same variables as
obj1.x and
obj1.y.
As you can see, the class is called by passing the values 7 and 8 to it. These
values are then assigned
to
x and
y within the class initializer method. We assign the class object to an identifier that we call
obj1.
The
obj1 identifier now holds a reference to
my_object() with the values we’ve passed it. The
obj1
identifier can now be used to call methods and functions that are defined within the class.
For more information on classes, please see Chapter 6, which covers object orientation in Python.
Classes are very powerful and the fundamental building blocks for making larger programs.
Statements
When we refer to statements, we are really referring to a line of code that contains an instruction that
does something. A statement tells the Python interpreter to perform a task. Ultimately, programs are
made up of a combination of expressions and statements. In this section, we will
take a tour of statement
keywords and learn how they can be used.
Let’s start out by listing each of these different statement keywords, and then we will go into more
detail about how to use each of them with different examples. I will not cover every statement keyword
in this section as some of them are better left for later in the chapter or the book, but you should have a
good idea of how to code an action which performs a task after reading through this section. While this
section will provide implementation details about the different statements, you should refer to later
chapters to find advanced uses of these features.
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
12
Table 1-2. Statement Keywords
if-elif-else
for
while
continue
break
try-except-finally
assert
def
print
del
raise
import
Now that we’ve taken a look at each of these keywords, it is time to look at each of them in detail. It
is important to remember that you cannot use any of these keywords for variable names.
if-elif-else Statement
The if statement simply performs an evaluation on an expression and does different things depending
on whether it is
True or
False. If the expression evaluates to
True then one set of statements will be
executed, and if it evaluates to
False a different set of statements will be executed. If statements are quite
often used for branching code into one direction or another based upon certain
values which have been
calculated or provided in the code.
Pseudocode would be as follows:
Listing 1-15.
if
:
perform an action
else:
perform a different action
Any number of if/else statements can be linked together in order to create a logical code branch.
When there are multiple expressions to be evaluated in the same statement, then the elif statement can
be used to link these expressions together. Note that each set of statements within an if-elif-else
statement must be indented with the conditional statement out-dented and the resulting set of
statements indented. Remember, a consistent indentation must be followed throughout the course of
the program. The if statement is a good example of how well the consistent use of indention helps
readability of a program. If you are coding in Java for example, you can space the code however you’d
like as long as you use the curly braces to enclose the statement. This can lead to code that is very hard to
read…the indentation which Python requires really shines through here.
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
13
Listing 1-16. Example of if statement
>>> x = 3
>>> y = 2
>>> if x == y:
... print 'x is equal to y'
... elif x > y:
... print 'x is greater than y'
... else:
... print 'x is less than y'
...
x is greater than y
While the code is simple,
it demonstrates that using an if statement can result in branching code
logic.
print Statement
The
print statement is used to display program output onto the screen (you’ve already seen it in action
several times). It can be used for displaying messages, which are printed from within a program, and also
for printing values, which may have been calculated. In order to display variable values within a print
statement, we need to learn how to use some of the formatting options that are available to Python. This
section will cover the basics of using the print statement along with how to
display values by formatting
your strings of text.
In the Java language, we need to make a call to the System library in order to print something to the
command line. In Python, this can be done with the use of the
print statement. The most basic use of the
print statement is to display a line of text. In order to do so, you simply enclose the text that you want to
display within single or double quotes. Take a look at the following example written in Java, and
compare it to the example immediately following which is rewritten in Python. I think you’ll see why the
print statement in Python makes life a bit easier.
Listing 1-17. Java Print Output Example
System.out.println("This text will be printed to the command line");
Listing 1-18. Python Print Output Example
print 'This text will be printed to the command line'
As you can see from this example, printing a line of text in Python is very straightforward. We can
also print variable values to the screen using the
print statement.
Listing 1-19.
>>> my_value = 'I love programming in Jython'
>>> print my_value
I love programming in Jython
www.it-ebooks.info