Chapter 1. About Python – The Quick Python Book

Chapter 1. About Python

This chapter covers

  • Why use Python?
  • What Python does well
  • What Python doesn’t do as well
  • Why learn Python 3?

Read this chapter if you want to know how Python compares to other languages and its place in the grand scheme of things. Skip this chapter if you want to start learning Python right away. The information in this chapter is a valid part of this book—but it’s certainly not necessary for programming with Python.

1.1. Why should I use Python?

Hundreds of programming languages are available today, from mature languages like C and C++, to newer entries like Ruby, C#, and Lua, to enterprise juggernauts like Java. Choosing a language to learn is difficult. Although no one language is the right choice for every possible situation, I think that Python is a good choice for a large number of programming problems, and it’s also a good choice if you’re learning to program. Hundreds of thousands of programmers around the world use Python, and the number grows every year.

Python continues to attract new users for a variety of reasons. It’s a true cross-platform language, running equally well on Windows, Linux/UNIX, and Macintosh platforms, as well as others, ranging from supercomputers to cell phones. It can be used to develop small applications and rapid prototypes, but it scales well to permit development of large programs. It comes with a powerful and easy-to-use graphical user interface (GUI) toolkit, web programming libraries, and more. And it’s free.

1.2. What Python does well

Python is a modern programming language developed by Guido van Rossum in the 1990s (and named after a famous comedic troupe). Although Python isn’t perfect for every application, its strengths make it a good choice for many situations.

1.2.1. Python is easy to use

Programmers familiar with traditional languages will find it easy to learn Python. All of the familiar constructs such as loops, conditional statements, arrays, and so forth are included, but many are easier to use in Python. Here are a few of the reasons why:

  • Types are associated with objects, not variables. A variable can be assigned a value of any type, and a list can contain objects of many different types. This also means that type casting usually isn’t necessary, and your code isn’t locked into the straitjacket of predeclared types.
  • Python typically operates at a much higher level of abstraction. This is partly the result of the way the language is built and partly the result of an extensive standard code library that comes with the Python distribution. A program to download a web page can be written in two or three lines!
  • Syntax rules are very simple. Although becoming an expert Pythonista takes time and effort, even beginners can absorb enough Python syntax to write useful code quickly.

Python is well suited for rapid application development. It isn’t unusual for coding an application in Python to take one-fifth the time it would if coded in C or Java and to take as little as one-fifth the number of lines of the equivalent C program. This depends on the particular application, of course; for a numerical algorithm performing mostly integer arithmetic in for loops, there would be much less of a productivity gain. For the average application, the productivity gain can be significant.

1.2.2. Python is expressive

Python is a very expressive language. Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages. The advantages of a more expressive language are obvious: the fewer lines of code you have to write, the faster you can complete the project. Not only that, but the fewer lines of code there are, the easier the program will be to maintain and debug.

To get an idea of how Python’s expressiveness can simplify code, let’s consider swapping the values of two variables, var1 and var2. In a language like Java, this requires three lines of code and an extra variable:

int temp = var1;
var1 = var2;
var2 = temp;

The variable temp is needed to save the value of var1 when var2 is put into it, and then that saved value is put into var2. The process isn’t terribly complex, but reading those three lines and understanding that a swap has taken place takes a certain amount of overhead, even for experienced coders.

In contrast, Python lets you make the same swap in one line and in a way that makes it obvious that a swap of values has occurred:

var2, var1 = var1, var2

Of course, this is a very simple example, but you find the same advantages throughout the language.

1.2.3. Python is readable

Another advantage of Python is that it’s easy to read. You might think that a programming language needs to be read only by a computer, but humans have to read your code as well—whoever debugs your code (quite possibly you), whoever maintains your code (could be you again), and whoever might want to modify your code in the future. In all of those situations, the easier the code is to read and understand, the better it is.

The easier code is to understand, the easier it is to debug, maintain, and modify. Python’s main advantage in this department is its use of indentation. Unlike most languages, Python insists that blocks of code be indented. Although this strikes some as odd, it has the benefit that your code is always formatted in a very easy-to-read style.

Following are two short programs, one written in Perl and one in Python. Both take two equal-sized lists of numbers and return the pairwise sum of those lists. I think the Python code is more readable than the Perl code; it’s visually cleaner and contains fewer inscrutable symbols:

# Perl version.
sub pairwise_sum {
my($arg1, $arg2) = @_;
my(@result) = ();
@list1 = @$arg1;
@list2 = @$arg2;
for($i=0; $i < length(@list1); $i++) {
push(@result, $list1[$i] + $list2[$i]);
}
return(\@result);
}
# Python version.
def pairwise_sum(list1, list2):
result = []
for i in range(len(list1)):
result.append(list1[i] + list2[i])
return result

Both pieces of code do the same thing, but the Python code wins in terms of readability.

1.2.4. Python is complete—“batteries included”

Another advantage of Python is its “batteries included” philosophy when it comes to libraries. The idea is that when you install Python, you should have everything you need to do real work, without the need to install additional libraries. This is why the Python standard library comes with modules for handling email, web pages, databases, operating system calls, GUI development, and more.

For example, with Python, you can write a web server to share the files in a directory with just two lines of code:

import http.server
http.server.test(HandlerClass=http.server.SimpleHTTPRequestHandler)

There’s no need to install libraries to handle network connections and HTTP—it’s already in Python, right out of the box.

1.2.5. Python is cross-platform

Python is also an excellent cross-platform language. Python runs on many different platforms: Windows, Mac, Linux, UNIX, and so on. Because it’s interpreted, the same code can run on any platform that has a Python interpreter, and almost all current platforms have one. There are even versions of Python that run on Java (Jython) and .NET (IronPython), giving you even more possible platforms that run Python.

1.2.6. Python is free

Python is also free. Python was originally, and continues to be, developed under the open source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal applications, and you don’t need to pay a dime.

Although attitudes are changing, some people are still leery of free software because of concerns about a lack of support, fearing they lack the clout of a paying customer. But Python is used by many established companies as a key part of their business; Google, Rackspace, Industrial Light & Magic, and Honeywell are just a few examples. These companies and many others know Python for what it is—a very stable, reliable, and well-supported product with an active and knowledgeable user community. You’ll get an answer to even the most difficult Python question more quickly on the Python internet newsgroup than you will on most tech-support phone lines, and the Python answer will be free and correct.

 

Python and open source software

Not only is Python free of cost, but its source code is also freely available, and you’re free to modify, improve, and extend it if you want. Because the source code is freely available, you have the ability to go in yourself and change it (or to hire someone to go in and do so for you). You rarely have this option at any reasonable cost with proprietary software.

If this is your first foray into the world of open source software, you should understand that not only are you free to use and modify Python, but you’re also able (and encouraged) to contribute to it and improve it. Depending on your circumstances, interests, and skills, those contributions might be financial, as in a donation to the Python Software Foundation (PSF), or they may involve participating in one of the special interest groups (SIGs), testing and giving feedback on releases of the Python core or one of the auxiliary modules, or contributing some of what you or your company develops back to the community. The level of contribution (if any) is, of course, up to you; but if you’re able to give back, definitely consider doing so. Something of significant value is being created here, and you have an opportunity to add to it.

 

Python has a lot going for it: expressiveness, readability, rich included libraries, and cross-platform capabilities, plus it’s open source. What’s the catch?

1.3. What Python doesn’t do as well

Although Python has many advantages, no language can do everything, so Python isn’t the perfect solution for all your needs. To decide whether Python is the right language for your situation, you also need to consider the areas where Python doesn’t do as well.

1.3.1. Python is not the fastest language

A possible drawback with Python is its speed of execution. It isn’t a fully compiled language. Instead, it’s first semicompiled to an internal byte-code form, which is then executed by a Python interpreter. There are some tasks, such as string parsing using regular expressions, for which Python has efficient implementations and is as fast as, or faster than, any C program you’re likely to write. Nevertheless, most of the time, using Python results in slower programs than a language like C. But you should keep this in perspective. Modern computers have so much computing power that for the vast majority of applications, the speed of the program isn’t as important as the speed of development, and Python programs can typically be written much more quickly. In addition, it’s easy to extend Python with modules written in C or C++, which can be used to run the CPU-intensive portions of a program.

1.3.2. Python doesn’t have the most libraries

Although Python comes with an excellent collection of libraries, and many more are available, Python doesn’t hold the lead in this department. Languages like C, Java, and Perl have even larger collections of libraries available, in some cases offering a solution where Python has none or a choice of several options where Python might have only one. These situations tend to be fairly specialized, however, and Python is easy to extend, either in Python itself or by using existing libraries in C and other languages. For almost all common computing problems, Python’s library support is excellent.

1.3.3. Python doesn’t check variable types at compile time

Unlike some languages, Python’s variables are more like labels that reference various objects: integers, strings, class instances, whatever. That means that although those objects themselves have types, the variables referring to them aren’t bound to that particular type. It’s possible (if not necessarily desirable) to use the variable x to refer to a string in one line and an integer in another:

The fact that Python associates types with objects and not with variables means that the interpreter doesn’t help you catch variable type mismatches. If you intend a variable count to hold an integer, Python won’t complain if you assign the string “two” to it. Traditional coders count this as a disadvantage, because you lose an additional free check on your code. But errors like this usually aren’t hard to find and fix, and Python’s testing features makes avoiding type errors manageable. Most Python programmers feel that the flexibility of dynamic typing more than outweighs the cost.

1.4. Why learn Python 3?

Python has been around for a number of years and has evolved over that time. The first edition of this book was based on Python 1.5.2, and Python 2.x has been the dominant version for several years. This book is based on Python 3.1.

Python 3, originally whimsically dubbed Python 3000, is notable because it’s the first version of Python in the history of the language to break backward compatibility. What this means is that code written for earlier versions of Python probably won’t run on Python 3 without some changes. In earlier versions of Python, for example, the print statement didn’t require parentheses around its arguments:

print "hello"

In Python 3, print is a function and needs the parentheses:

print("hello")

You may be thinking, “Why change details like this, if it’s going to break old code?” Because this kind of change is a big step for any language, the core developers of Python thought about this issue carefully. Although the changes in Python 3 break compatibility with older code, those changes are fairly small and for the better—they make the language more consistent, more readable, and less ambiguous. Python 3 isn’t a dramatic rewrite of the language; it’s a well-thought-out evolution. The core developers also took care to provide a strategy and tools to safely and efficiently migrate old code to Python 3, which will be discussed in a later chapter.

Why learn Python 3? Because it’s the best Python so far; and as projects switch to take advantage of its improvements, it will be the dominant Python version for years to come. If you need a library that hasn’t been converted yet, by all means stick with Python 2.x; but if you’re starting to learn Python or starting a project, then go with Python 3—not only is it better, but it’s the future.

1.5. Summary

Python is a modern, high-level language, with many features:

  • Dynamic typing
  • Simple, consistent syntax and semantics
  • Multiplatform
  • Well-planned design and evolution of features
  • Highly modular
  • Suited for both rapid development and large-scale programming
  • Reasonably fast and easily extended with C or C++ modules for higher speeds
  • Easy access to various GUI toolkits
  • Built-in advanced features such as persistent object storage, advanced hash tables, expandable class syntax, universal comparison functions, and so forth
  • Powerful included libraries such as numeric processing, image manipulation, user interfaces, web scripting, and others
  • Supported by a dynamic Python community
  • Can be integrated with a number of other languages to let you take advantage of the strengths of both while obviating their weaknesses

Let’s get going. The first step is to make sure you have Python 3 installed on your machine. In the next chapter, we’ll look at how to get Python up and running on Windows, Mac, and Linux platforms.