CHAPTER 1
■
LANGUAGE
AND SYNTAX
17
import Statement
A program can be made up of one or more suites of code. In order to save a program so that it can be
used later, we place the code into files on our computer. Files that contain Python code should contain a
.py suffix such as my_code.py and so forth. These files are known as modules in the Python world. The
import statement is used much like it is in other languages, it brings external modules or code into a
program so that it can be used. This statement is ultimately responsible for reuse of code in multiple
locations. The
import statement allows us to save code into a flat file or script, and then use it in an
application at a later time.
If a class is stored in an external module that is named the same as the class itself, the
import
statement can be used to explicitly bring that class into an application.
Similarly, if you wish to import
only a specific identifier from another module into your current module, then the specific code can be
named within using the syntax
from <> import <>. Time to see some examples.
Listing 1-29.
# Import a module named TipCalculator
import TipCalculator
# Import a function tipCalculator from within a module called ExternalModule.py
from ExternalModule import tipCalculator
When importing modules into your program, you must ensure that the module being imported does
not conflict with another name in your current program. To import a module
that is named the same as
another identifier in your current program, you can use the
as syntax. In the following example, let’s
assume that we have defined an external module with the name of
tipCalculator.py and we want to use
it’s functionality in our current program. However, we already have a function named
tipCalculator()
within the current program. Therefore, we use the
as syntax to refer to the
tipCalculator module.
Listing 1-30.
import
tipCalculator as tip
This section just touches the surface of importing and working with external modules. For a more
detailed discussion, please visit Chapter 7 which covers this topic specifically.
Iteration
The Python language has several iteration structures which are used to traverse through a series of items
in a list, database records, or any other type of collection. A list in Python is a container that holds
objects or values and can be indexed. For instance, we create a list of numbers in the following example.
We then obtain the second element in the list by using the index value of 1 (indexing starts at zero, so the
first element of the list is my_numbers[0]).
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
18
Listing 1-31.
>>> my_numbers = [1, 2, 3, 4, 5]
>>> my_numbers
[1, 2, 3, 4, 5]
>>> my_numbers[1]
2
For
more information on lists, please see Chapter 2 that goes into detail about lists and other
containers that can be used in Python.
The most commonly used iteration structure within the language is probably the
for loop, which is
known for its easy syntax and practical usage.
Listing 1-32.
>>> for value in my_numbers:
... print value
...
1
2
3
4
5
However, the
while loop still plays an important role in iteration, especially when you are not
dealing with collections of data, but rather working with conditional expressions. In this simple example,
we use a
while loop to iterate over the contents of
my_numbers.
Note that the len() function just returns
the number of elements that are contained in the list.
Listing 1-33.
>>> x = 0
>>> while x < len(my_numbers):
... print my_numbers[x]
... x = x + 1
...
1
2
3
4
5
This section will take you though each of these two iteration structures and touch upon the basics of
using them. The
while loop is relatively basic in usage, whereas there are many different
implementations and choices when using the
for loop. I will only touch upon the
for loop from
a high-
level perspective in this introductory chapter, but if you wish to go more in-depth then please visit
Chapter 3.
www.it-ebooks.info
CHAPTER 1
■
LANGUAGE AND SYNTAX
19
While Loop
The
while loop construct is used in order to iterate through code based upon a provided conditional
statement. As long as the condition is true, then the loop will continue to process. Once the condition
evaluates to false, the looping ends. The pseudocode for
while loop logic reads as follows:
while True
perform operation
The loop begins
with the declaration of the while and conditional expression, and it ends once the
conditional has been met and the expression is
True. The expression is checked at the beginning of each
looping sequence, so normally some value that is contained within the expression is changed within the
suite of statements inside the loop. Eventually the value is changed in such a way that it makes the
expression evaluate to False, otherwise an infinite loop would occur. Keep in mind that we need to
indent each of the lines
of code that exist within the while loop. This not only helps the code to maintain
readability, but it also allows Python to do away with the curly braces!
Listing 1-34. Example of a Java While Loop
int x = 9;
int y = 2;
int z = x – y;
while (y < x){
System.out.println("y is " + z + " less than x");
y = y++;
}
Now, let’s see the same code written in Python.
Listing 1-35. Example of a Python While Loop
>>> x = 9
>>> y = 2
>>> while y < x:
... print 'y is %d less than x' % (x-y)
... y += 1
...
y is 7 less than x
y is 6 less than x
y is 5 less than x
y is 4 less than x
y is 3 less than x
y is 2 less than x
y is 1 less than x
In this example, you
can see that the conditional y < x is evaluated each time the loop passes. Along
the way, we increment the value of
y by one each time we iterate, so that eventually
y is no longer less
than
x and the loop ends.
www.it-ebooks.info