CHAPTER 1
■
LANGUAGE AND SYNTAX
5
that you’ve installed Jython where you will find the file. It would be best to place this directory within
your PATH environment variable on either Windows, *NIX, or OS X machines so that you can fire up
Jython from within any directory on your machine. Once you’ve done this then you should be able to
open up a terminal or command prompt and type “jython” then hit enter to invoke the interactive
interpreter. This is where our journey begins! The Jython interactive interpreter is a great place to
evaluate code and learn the language. It is a real-time testing environment that allows you to type code
and instantly see the result. As you are reading through this chapter, I recommend you open up the
Jython interpreter and follow along with the code examples.
Identifiers and Declaring Variables
Every programming language needs to contain the ability to capture or calculate values and store them.
Python is no exception, and doing so is quite easy. Defining variables in Python is very similar to other
languages such as Java, but there are a few differences that you need to note.
To define a variable in the Python language, you simply name it using an identifier. An identifier is a
name that is used to identify an object. The language treats the variable name as a label that points to a
value. It does not give any type for the value. Therefore, this allows any variable to hold any type of data.
It also allows the ability of having one variable contain of different data types throughout the life cycle of
a program. So a variable that is originally assigned with an integer, can later contain a String. Identifiers
in Python can consist of any ordering of letters, numbers, or underscores. However, an identifier must
always begin with a non-numeric character value. We can use identifiers to name any type of variable,
block, or object in Python. As with most other programming languages, once an identifier is defined, it
can be referenced elsewhere in the program.
Once declared, a variable is untyped and can take any value. This is one difference between using a
statically typed language such as Java, and using dynamic languages like Python. In Java, you need to
declare the type of variable which you are creating, and you do not in Python. It may not sound like very
much at first, but this ability can lead to some extraordinary results. Consider the following two listings,
lets define a value ‘x’ below and we’ll give it a value of zero.
Listing 1-1. Java – Declare Variable
int x = 0;
Listing 1-2. Python – Declare Variable
x = 0
As you see, we did not have to give a type to this variable. We simply choose a name and assign it a
value. Since we do not need to declare a type for the variable, we can change it to a different value and
type later in the program.
Listing 1-3.
x = 'Hello Jython'
We’ve just changed the value of the variable ‘x’ from a numeric value to a String without any
consequences. What really occurred is that we created a new variable ‘Hello Jython’ and assigned it to
the identifier ‘x’, which in turn lost its reference to 0. This is a key to the dynamic language philosophy. .
.change should not be difficult.
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
6
Let us take what we know so far and apply it to some simple calculations. Based upon the definition
of a variable in Python, we can assign an integer value to a variable, and change it to a float at a later
point. For instance:
Listing 1-4.
>>> x = 6
>>> y = 3.14
>>> x = x * y
>>> print x
18.84
In the previous example, we’ve demonstrated that we can dynamically change the type of any given
variable by simply performing a calculation upon it. In other languages such as Java, we would have had
to begin by assigning a float type to the ‘x’ variable so that we could later change its value to a float. Not
here, Python allows us to bypass type constriction and gives us an easy way to do it.
Reserved Words
There are a few more rules to creating identifiers that we must follow in order to adhere to the Python
language standard. Certain words are not to be used as identifiers as the Python language reserves them
for performing a specific role within our programs. These words which cannot be used are known as
reserved words. If we try to use one of these reserved words as an identifier, we will see a SyntaxError
thrown as Python wants these reserved words as its own.
There are no symbols allowed in identifiers. Yes, that means the Perl developers will have to get used
to defining variables without the $.
Table 1-1 lists all of the Python language reserved words:
Table 1-1. Reserved Words
and
assert
break class
continue
def
del
elif
else
except
exec
finally for
from
global
or
pass
print
raise
return
try
while
with
yield
It is important to take care when naming variables so that you do not choose a name that matches
one of the module names from the standard library.
Coding Structure
Another key factor in which Python differs from other languages is its coding structure. Back in the day,
we had to develop programs based upon a very strict structure such that certain pieces must begin and
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
7
end within certain punctuations. Python uses indentation rather than punctuation to define the
structure of code. Unlike languages such as Java that use brackets to open or close a code block, Python
uses spacing as to make code easier to read and also limit unnecessary symbols in your code. It strictly
enforces ordered and organized code but it lets the programmer define the rules for indentation,
although a standard of four characters exists.
For instance, let’s jump ahead and look at a simple ‘if’ statement. Although you may not yet be
familiar with this construct, I think you will agree that it is easy to determine the outcome. Take a look at
the following block of code written in Java first, and then we’ll compare it to the Python equivalent.
Listing 1-5. Java if-statement
x = 100;
if(x > 0){
System.out.println("Wow, this is Java");
} else {
System.out.println("Java likes curly braces");
}
Now, let’s look at a similar block of code written in Python.
Listing 1-6. Python if-statement
x = 100
if x > 0:
print 'Wow, this is elegant'
else:
print 'Organization is the key'
Okay, this is cheesy but we will go through it nonetheless as it is demonstrating a couple of key
points to the Python language. As you see, the Python program evaluates if the value of the variable ‘x’ is
greater than zero. If so, it will print ‘Wow, this is elegant.’ Otherwise, it will print ‘Organization is the
key.’ Look at the indentation which is used within the ‘if’ block. This particular block of code uses four
spaces to indent the ‘print’ statement from the initial line of the block. Likewise, the ‘else’ jumps back to
the first space of the line and its corresponding implementation is also indented by four spaces. This
technique must be adhered to throughout an entire Python application. By doing so, we gain a couple of
major benefits: easy-to-read code and no need to use curly braces. Most other programming languages
such as Java use a bracket “[” or curly brace “{” to open and close a block of code. There is no need to do
so when using Python as the spacing takes care of this for you. Less code = easier to read and maintain. It
is also worth noting that the Java code in the example could have been written on one line, or worse, but
we chose to format it nicely.
Python ensures that each block of code adheres to its defined spacing strategy in a consistent
manner. What is the defined spacing strategy? You decide. As long as the first line of a code block is out-
dented by at least one space, the rest of the block can maintain a consistent indentation, which makes
code easy to read. Many argue that it is the structuring technique that Python adheres to which makes
them so easy to read. No doubt, adhering to a standard spacing throughout an application makes for
organization. As mentioned previously, the Python standard spacing technique is to use four characters
for indentation. If you adhere to these standards then your code will be easy to read and maintain in the
future. Your brain seems hard-wired to adhering to some form of indentation, so Python and your brain
are wired up the same way.
www.it-ebooks.info
Dostları ilə paylaş: |