




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































Python is a high-level scripting language which can be used for a wide variety of text processing, system administration and internet-related tasks. Unlike many similar languages, it’s core language is very small and easy to mas- ter, while allowing the addition of modules to perform a virtually limitless variety of tasks. Python is a true object-oriented language, and is available on a wide variety of platforms. There’s even a python interpreter written entirely in Java, further enhancing python’s position as an excellent solution for internet-based problems. Python was developed in the early 1990’s by Guido van Rossum, then at CWI in Amsterdam, and currently at CNRI in Virginia. In some ways, python grew out of a project to design a computer language which would be easy for beginners to learn, yet would be powerful enough for even advanced users. This heritage is reflected in python’s small, clean syntax and the thor- oughness of the implementation of ideas like object-oriented programming, without eliminating the ability to program in a more traditional style. So python is an excellent choice as a first programming language without sacri- ficing the power and advanced capabilities that users will eventually need. Although pictures of snakes often appear on python books and websites, the name is derived from Guido van Rossum’s favorite TV show, “Monty Python’s Flying Circus”. For this reason, lots of online and print documen- tation for the language has a light and humorous touch. Interestingly, many experienced programmers report that python has brought back a lot of the
7
fun they used to have programming, so van Rossum’s inspiration may be well expressed in the language itself.
1.2 The very Basics of Python
There are a few features of python which are different than other program- ming languages, and which should be mentioned early on so that subsequent examples don’t seem confusing. Further information on all of these features will be provided later, when the topics are covered in depth. Python statements do not need to end with a special character – the python interpreter knows that you are done with an individual statement by the presence of a newline, which will be generated when you press the “Return” key of your keyboard. If a statement spans more than one line, the safest course of action is to use a backslash () at the end of the line to let python know that you are going to continue the statement on the next line; you can continue using backslashes on additional continuation lines. (There are situations where the backslashes are not needed which will be discussed later.) Python provides you with a certain level of freedom when composing a program, but there are some rules which must always be obeyed. One of these rules, which some people find very surprising, is that python uses in- dentation (that is, the amount of white space before the statement itself) to indicate the presence of loops, instead of using delimiters like curly braces ({}) or keywords (like “begin” and “end”) as in many other languages. The amount of indentation you use is not important, but it must be consistent within a given depth of a loop, and statements which are not indented must begin in the first column. Most python programmers prefer to use an edi- tor like emacs, which automatically provides consistent indentation; you will probably find it easier to maintain your programs if you use consistent in- dentation in every loop, at all depths, and an intelligent editor is very useful in achieving this.
1.3 Invoking Python
There are three ways to invoke python, each with its’ own uses. The first way is to type “python” at the shell command prompt. This brings up the
word = ’python’ for i in word: ... print i ... p y t h o n
The need for a completely blank line is peculiar to the interactive use of python. In other settings, simply returning to the previous level of indenta- tion informs python that you’re closing the loop. You can terminate an interactive session by entering the end-of-file charac- ter appropriate to your system (control-Z for Windows, control-D for Unix), or by entering
import sys sys.exit()
or
raise SystemExit
at the python prompt. For longer programs, you can compose your python code in the editor of your choice, and execute the program by either typing “python”, followed by the name of the file containing your program, or by clicking on the file’s icon, if you’ve associated the suffix of your python file with the python in- terpreter. The file extension most commonly used for python files is “.py”. Under UNIX systems, a standard technique for running programs written in languages like python is to include a specially formed comment as the first line of the file, informing the shell where to find the interpreter for your program. Suppose that python is installed as /usr/local/bin/python on your system. (The UNIX command “which python” should tell you where python is installed if it’s not in /usr/local/bin.) Then the first line of your python program, starting in column 1, should look like this:
#!/usr/local/bin/python
After creating a file, say myprogram.py, which contains the special comment as its first line, you would make the file executable (through the UNIX com- mand “chmod +x myprogram.py”), and then you could execute your pro- gram by simply typing “myprogram.py” at the UNIX prompt. When you’re running python interactively, you can instruct python to ex- ecute files containing python programs with the execfile function. Suppose that you are using python interactively, and wish to run the program you’ve stored in the file myprog.py. You could enter the following statement:
execfile("myprog.py")
The file name, since it is not an internal python symbol (like a variable name or keyword), must be surrounded by quotes.
1.4 Basic Principles of Python
Python has many features that usually are found only in languages which are much more complex to learn and use. These features were designed into python from its very first beginnings, rather than being accumulated into an end result, as is the case with many other scripting languages. If you’re new to programming, even the basic descriptions which follow may seem intimidating. But don’t worry – all of these ideas will be made clearer in the chapters which follow. The idea of presenting these concepts now is to make you aware of how python works, and the general philosophy behind python programming. If some of the concepts that are introduced here seem abstract or overly complex, just try to get a general feel for the idea, and the details will be fleshed out later
Python is designed so that there really isn’t that much to learn in the basic language. For example, there is only one basic structure for conditional pro- gramming (if/else/elif), two looping commands (while and for), and a consistent method of handling errors (try/except) which apply to all python programs. This doesn’t mean that the language is not flexible and powerful, however. It simply means that you’re not confronted with an overwhelming choice of options at every turn, which can make programming a much simpler task.
when used with different types of data. For example, in python, when you’re dealing with numbers, the plus sign (+) has its usual obvious meaning of addition. But when you’re dealing with strings, the plus sign means to join the two strings together. In addition to being able to use overloading for built-in types (like numbers and strings), python also allows you to define what operators mean for the data types you create yourself. Perhaps the nicest feature of object-oriented programming in python is that you can use as much or as little of it as you want. Until you get comfortable with the ideas behind object-oriented programming, you can write more traditional programs in python without any problems.
When you type the name of a variable inside a script or interactive python session, python needs to figure out exactly what variable you’re using. To prevent variables you create from overwriting or interfering with variables in python itself or in the modules you use, python uses the concept of multiple namespaces. Basically, this means that the same variable name can be used in different parts of a program without fear of destroying the value of a variable you’re not concerned with. To keep its bookkeeping in order, python enforces what is known as the LGB rule. First, the local namespace is searched, then the global names- pace, then the namespace of python built-in functions and variables. A local namespace is automatically created whenever you write a function, or a module containing any of functions, class definitions, or methods. The global namespace consists primarily of the variables you create as part of the “top- level” program, like a script or an interactive session. Finally, the built-in namespace consists of the objects which are part of python’s core. You can see the contents of any of the namespaces by using the dir command:
dir() [’builtins’, ’doc’, ’name’] dir(builtins) [’ArithmeticError’, ’AssertionError’, ’AttributeError’, ’EOFError’, ’Ellipsis’, ’Exception’, ’FloatingPointError’, ’IOError’, ’ImportError’, ’IndexError’, ’KeyError’, ’KeyboardInterrupt’, ’LookupError’, ’MemoryError’, ’NameError’, ’None’, ’OverflowError’, ’RuntimeError’, ’StandardError’, ’SyntaxError’, ’SystemError’, ’SystemExit’, ’TypeError’, ’ValueError’, ’ZeroDivisionError’, ’_’, ’debug’, ’doc’,
’import’, ’name’, ’abs’, ’apply’, ’callable’, ’chr’, ’cmp’, ’coerce’, ’compile’, ’complex’, ’delattr’, ’dir’, ’divmod’, ’eval’, ’execfile’, ’filter’, ’float’, ’getattr’, ’globals’, ’hasattr’, ’hash’, ’hex’, ’id’, ’input’, ’int’, ’intern’, ’isinstance’, ’issubclass’, ’len’, ’list’, ’locals’, ’long’, ’map’, ’max’, ’min’, ’oct’, ’open’, ’ord’, ’pow’, ’range’, ’raw_input’, ’reduce’, ’reload’, ’repr’, ’round’, ’setattr’, ’slice’, ’str’, ’tuple’, ’type’, ’vars’, ’xrange’]
The builtins namespace contains all the functions, variables and ex- ceptions which are part of python’s core. To give controlled access to other namespaces, python uses the import statement. There are three ways to use this statement. In its simplest form, you import the name of a module; this allows you to specify the various objects defined in that module by using a two level name, with the mod- ule’s name and the object’s name separated by a period. For example, the string module (Section 8.4) provides many functions useful for dealing with character strings. Suppose we want to use the split function of the string module to break up a sentence into a list containing separate words. We could use the following sequence of statements:
import string string.split(’Welcome to the Ministry of Silly Walks’) [’Welcome’, ’to’, ’the’, ’Ministry’, ’of’, ’Silly’, ’Walks’]
If we had tried to refer to this function as simply “split”, python would not be able to find it. That’s because we have only imported the string module into the local namespace, not all of the objects defined in the module. (See below for details of how to do that.) The second form of the import statement is more specific; it specifies the individual objects from a module whose names we want imported into the local namespace. For example, if we only needed the two functions split and join for use in a program, we could import just those two names directly into the local namespace, allowing us to dispense with the string. prefix:
from string import split,join split(’Welcome to the Ministry of Silly Walks’) [’Welcome’, ’to’, ’the’, ’Ministry’, ’of’, ’Silly’, ’Walks’]
This technique reduces the amount of typing we need to do, and is an efficient way to bring just a few outside objects into the local environment.
File "div.py", line 5, in? print x/y ZeroDivisionError: integer division or modulo
While the message may look a little complicated, the main point to notice is that the last line of the message tells us the name of the exception that occured. This allows us to construct an except clause to handle the problem:
x = 7 y = 0
try: print x/y except ZeroDivisionError: print "Oops - I can’t divide by zero, sorry!"
print "Now we’re done!"
Now when we run the program, it behaves a little more nicely:
% div.py Oops - I can’t divide by zero, sorry! Now we’re done!
Since each exception in python has a name, it’s very easy to modify your program to handle errors whenever they’re discovered. And of course, if you can think ahead, you can construct try/except clauses to catch errors before they happen.
Strings are a collection of characters which are stored together to represent arbitrary text inside a python program. You can create a string constant inside a python program by surrounding text with either single quotes (’), double quotes ("), or a collection of three of either types of quotes (’’’ or """). In the first two cases, the opening and closing quotes must appear on the same line in your program; when you use triple quotes, your text can span as many lines as you like. The choice of which quote symbol to use is up to you – both single and double quotes have the same meaning in python. Here are a few examples of how to create a string constant and assign its value to a variable:
name = ’Phil’ value = "$7.00" helptext = """You can create long strings of text spanning several lines by using triple quotes at the beginning and end of the text"""
When the variable helptext is printed (using the print command; Sec- tion 5.1), it would display as three lines, with the line breaks at the same points as in the triple-quoted text. You can also create strings by reading input from a file (Section 5.4.1), or by concatenating smaller strings (Section 2.4.1).
17
called raw strings, in which the character sequences shown in Table 2.1 have no special meaning. To construct a raw string, precede the opening quote character with either a lowercase or uppercase “R” (r or R). Note, however that a backslash cannot be the very last character of a raw string. Thus, these two expressions are equivalent:
print ’Here is a backslash: \ ’ Here is a backslash:
print r’Here is a backslash: \ ’ Here is a backslash: \
2.3 Unicode Strings
Starting with version 2.0, python provides support for Unicode strings, whose characters are stored in 16 bits instead of the 8 bits used by a normal string. To specify that a string should be stored using this format, precede the open- ing quote character with either a lowercase or uppercase “U”. In addition, an arbitrary Unicode character can be specified with the notation “\uhhhh”, where hhhh represents a four-digit hexadecimal number. Notice that if a unicode string is combined with a regular string, the resulting string will also be a Unicode string.
2.4 String Operations
The following subsections describe some of the operations that are available with strings.
The addition operator (+) takes on the role of concatenation when used with strings, that is, the result of “adding” two strings together is a new string which consists of the original strings put together:
first = ’black’ second = ’jack’ first + second ’blackjack’
No space or other character is inserted between concatenated strings. If you do want a space, you can simply add it:
first + " " + second ’black jack’
When the strings you want to concatenate are literal string constants, that is, pieces of text surrounded by any of the quotes that python accepts, you don’t even need the plus sign; python will automatically concatenate string constants that are separated by whitespace:
nums = "one " "two " "three " nums ’one two three ’
You can freely mix variables and string constants together — anywhere that python expects a string, it can be either a variable or a constant:
msg = """Send me email ... My address is """ msg + "[email protected]" ’Send me email\012My address is [email protected]’
Notice that the newline which was entered in the triple quoted string appears as \012, the octal representation of the (non-printable) newline character. When you use the print command, the newline is displayed as you would expect:
print msg + ’[email protected]’ Send me email My address is [email protected]
Remember that python considers the type of an object when it tries to apply an operator, so that if you try to concatenate a string and a number, you’ll have problems:
x = 12./7. print ’The answer is ’ + x Traceback (innermost last): File "
", line 1, in? TypeError: illegal argument type for built-in operation