Text
stringlengths
1
9.41k
Python is sometimes used to construct websites, but it’s also widely used in nearly every other computer domain, from robotics to movie animation. - Is more mature and has a more readable syntax than Ruby.
Unlike Ruby and Java, OOP is an option in Python—Python does not impose OOP on users or projects to which it may not apply. - Has the dynamic flavor of languages like SmallTalk and Lisp, but also has a simple, traditional syntax accessible to developers as well as end users of customizable systems. Especially for pr...
Furthermore, unless your application requires peak performance, Python is often a viable alternative to systems development languages such as C, C++, and Java: Python code will be much less difficult to write, debug, and maintain. Of course, your author has been a card-carrying Python evangelist since 1992, so take th...
They do, however, reflect the common experience of many developers who have taken time to explore what Python has to offer. ###### Chapter Summary And that concludes the hype portion of this book.
In this chapter, we’ve explored some of the reasons that people pick Python for their programming tasks.
We’ve also seen how it is applied and looked at a representative sample of who is using it today. My goal is to teach Python, though, not to sell it.
The best way to judge a language is to see it in action, so the rest of this book focuses entirely on the language details we’ve glossed over here. The next two chapters begin our technical introduction to the language.
In them, we’ll explore ways to run Python programs, peek at Python’s byte code execution model, and introduce the basics of module files for saving code.
The goal will be to give you **|** ----- just enough information to run the examples and exercises in the rest of the book.
You won’t really start programming per se until Chapter 4, but make sure you have a handle on the startup details before moving on. ###### Test Your Knowledge: Quiz In this edition of the book, we will be closing each chapter with a quick pop quiz about the material presented therein to help you review the key concep...
The answers for these quizzes appear immediately after the questions, and you are encouraged to read the answers once you’ve taken a crack at the questions yourself.
In addition to these end-of-chapter quizzes, you’ll find lab exercises at the end of each part of the book, designed to help you start coding Python on your own.
For now, here’s your first test. Good luck! 1. What are the six main reasons that people choose to use Python? 2. Name four notable companies or organizations using Python today. 3.
Why might you not want to use Python in an application? 4. What can you do with Python? 5. What’s the significance of the Python import this statement? 6.
Why does “spam” show up in so many Python examples in books and on the Web? 7. What is your favorite color? ###### Test Your Knowledge: Answers How did you do?
Here are the answers I came up with, though there may be multiple solutions to some quiz questions.
Again, even if you’re sure you got a question right, I encourage you to look at these answers for additional context.
See the chapter’s text for more details if any of these responses don’t make sense to you. 1.
Software quality, developer productivity, program portability, support libraries, component integration, and simple enjoyment.
Of these, the quality and productivity themes seem to be the main reasons that people choose to use Python. 2.
Google, Industrial Light & Magic, EVE Online, Jet Propulsion Labs, Maya, ESRI, and many more.
Almost every organization doing software development uses Python in some fashion, whether for long-term strategic product development or for short-term tactical tasks such as testing and system administration. 3.
Python’s downside is performance: it won’t run as quickly as fully compiled languages like C and C++.
On the other hand, it’s quick enough for most applications, and typical Python code runs at close to C speed anyhow because it invokes **|** ----- linked-in C code in the interpreter.
If speed is critical, compiled extensions are available for number-crunching parts of an application. 4.
You can use Python for nearly anything you can do with a computer, from website development and gaming to robotics and spacecraft control. 5.
import this triggers an Easter egg inside Python that displays some of the design philosophies underlying the language. You’ll learn how to run this statement in the next chapter. 6.
“Spam” is a reference from a famous Monty Python skit in which people trying to order food in a cafeteria are drowned out by a chorus of Vikings singing about spam.
Oh, and it’s also a common variable name in Python scripts.... 7. Blue.
No, yellow! ###### Python Is Engineering, Not Art When Python first emerged on the software scene in the early 1990s, it spawned what is now something of a classic conflict between its proponents and those of another popular scripting language, Perl.
Personally, I think the debate is tired and unwarranted today—developers are smart enough to draw their own conclusions.
Still, this is one of the most common topics I’m asked about on the training road, so it seems fitting to say a few words about it here. The short story is this: you can do everything in Python that you can in Perl, but you can _read your code after you do it.
That’s it—their domains largely overlap, but Python is_ more focused on producing readable code.
For many, the enhanced readability of Python translates to better code reusability and maintainability, making Python a better choice for programs that will not be written once and thrown away.
Perl code is easy to write, but difficult to read.
Given that most software has a lifespan much longer than its initial creation, many see Python as a more effective tool. The somewhat longer story reflects the backgrounds of the designers of the two languages and underscores some of the main reasons people choose to use Python.
Python’s creator is a mathematician by training; as such, he produced a language with a high degree of uniformity—its syntax and toolset are remarkably coherent.
Moreover, like math, Python’s design is orthogonal—most of the language follows from a small set of core concepts.
For instance, once one grasps Python’s flavor of polymorphism, the rest is largely just details. By contrast, the creator of the Perl language is a linguist, and its design reflects this heritage.
There are many ways to accomplish the same tasks in Perl, and language constructs interact in context-sensitive and sometimes quite subtle ways—much like natural language.
As the well-known Perl motto states, “There’s more than one way to do it.” Given this design, both the Perl language and its user community have historically encouraged freedom of expression when writing code.
One person’s Perl code can be radically different from another’s.
In fact, writing unique, tricky code is often a source of pride among Perl users. **|** ----- **|** ----- ----- ###### CHAPTER 2 ### How Python Runs Programs This chapter and the next take a quick look at program execution—how you launch code, and how Python runs it.
In this chapter, we’ll study the Python interpreter. Chapter 3 will then show you how to get your own programs up and running. Startup details are inherently platform-specific, and some of the material in these two chapters may not apply to the platform you work on, so you should feel free to skip parts not relevant t...
Likewise, more advanced readers who have used similar tools in the past and prefer to get to the meat of the language quickly may want to file some of this chapter away as “for future reference.” For the rest of you, let’s learn how to run some code. ###### Introducing the Python Interpreter So far, I’ve mostly been ...
But, as currently implemented, it’s also a software package called an interpreter. An interpreter is a kind of program that executes other programs.
When you write a Python program, the Python interpreter reads your program and carries out the instructions it contains. In effect, the interpreter is a layer of software logic between your code and the computer hardware on your machine. When the Python package is installed on your machine, it generates a number of co...
Depending on how you use it, the Python interpreter may take the form of an executable program, or a set of libraries linked into another program.
Depending on which flavor of Python you run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else.
Whatever form it takes, the Python code you write must always be run by this interpreter.
And to enable that, you must install a Python interpreter on your computer. Python installation details vary by platform and are covered in more depth in Appendix A.
In short: ----- - Windows users fetch and run a self-installing executable file that puts Python on their machines.
Simply double-click and say Yes or Next at all prompts. - Linux and Mac OS X users probably already have a usable Python preinstalled on their computers—it’s a standard component on these platforms today. - Some Linux and Mac OS X users (and most Unix users) compile Python from its full source code distribution pac...
For instance, Python is available on cell phones, game consoles, and iPods, but installation details vary widely. Python itself may be fetched from the downloads page on the website, _http://www_ _.python.org.
It may also be found through various other distribution channels. Keep in_ mind that you should always check to see whether Python is already present before installing it.
If you’re working on Windows, you’ll usually find Python in the Start menu, as captured in Figure 2-1 (these menu options are discussed in the next chapter). On Unix and Linux, Python probably lives in your /usr directory tree. Because installation details are so platform-specific, we’ll finesse the rest of this story...
For more details on the installation process, consult Appendix A.
For the purposes of this chapter and the next, I’ll assume that you’ve got Python ready to go. ###### Program Execution What it means to write and run a Python script depends on whether you look at these tasks as a programmer, or as a Python interpreter.
Both views offer important perspectives on Python programming. ###### The Programmer’s View In its simplest form, a Python program is just a text file containing Python statements. For example, the following file, named script0.py, is one of the simplest Python scripts I could dream up, but it passes for a fully func...
I’ll explain the print statement, and why you can raise 2 to the power 100 in Python without overflowing, in the next parts of this book. **|** ----- _Figure 2-1.
When installed on Windows, this is how Python shows up in your Start button menu.
This_ _can vary a bit from release to release, but IDLE starts a development GUI, and Python starts a simple_ _interactive session.
Also here are the standard manuals and the PyDoc documentation engine (Module_ _Docs)._ You can create such a file of statements with any text editor you like.
By convention, Python program files are given names that end in .py; technically, this naming scheme is required only for files that are “imported,” as shown later in this book, but most Python files have .py names for consistency. After you’ve typed these statements into a text file, you must tell Python to execute t...
As you’ll see in the next chapter, you can launch Python program files **|** ----- by shell command lines, by clicking their icons, from within IDEs, and with other standard techniques.
If all goes well, when you execute the file, you’ll see the results of the two print statements show up somewhere on your computer—by default, usually in the same window you were in when you ran the program: ``` hello world 1267650600228229401496703205376 ``` For example, here’s what happened when I ran this scrip...
We probably won’t win any programming awards with this code, but it’s enough to capture the basics of program execution. ###### Python’s View The brief description in the prior section is fairly standard for scripting languages, and it’s usually all that most Python programmers need to know.
You type code into text files, and you run those files through the interpreter.
Under the hood, though, a bit more happens when you tell Python to “go.” Although knowledge of Python internals is not strictly required for Python programming, a basic understanding of the runtime structure of Python can help you grasp the bigger picture of program execution. When you instruct Python to run your scri...
Specifically, it’s first compiled to something called “byte code” and then routed to something called a “virtual machine.” ###### Byte code compilation Internally, and almost completely hidden from you, when you execute a program Python first compiles your source code (the statements in your file) into a format known...
Compilation is simply a translation step, and byte code is a lower-level, platform-independent representation of your source code.
Roughly, Python translates each of your source statements into a group of byte code instructions by decomposing them into individual steps.
This byte code translation is performed to speed execution—byte code can be run much more quickly than the original source code statements in your text file. You’ll notice that the prior paragraph said that this is almost completely hidden from you.
If the Python process has write access on your machine, it will store the byte code of your programs in files that end with a .pyc extension (“.pyc” means compiled “.py” source).
You will see these files show up on your computer after you’ve run a few **|** ----- programs alongside the corresponding source code files (that is, in the same directories). Python saves byte code like this as a startup speed optimization.
The next time you run your program, Python will load the .pyc files and skip the compilation step, as long as you haven’t changed your source code since the byte code was last saved.
Python automatically checks the timestamps of source and byte code files to know when it must recompile—if you resave your source code, byte code is automatically re-created the next time your program is run. If Python cannot write the byte code files to your machine, your program still works— the byte code is generat...
Byte code files are also one way to ship Python programs—Python is happy to run a program if all it can find are .pyc files, even if the original .py source files are absent.
(See “Frozen Binaries” on page 32 for another shipping option.) ###### The Python Virtual Machine (PVM) Once your program has been compiled to byte code (or the byte code has been loaded from existing .pyc files), it is shipped off for execution to something generally known as the Python Virtual Machine (PVM, for the...
The PVM sounds more impressive than it is; really, it’s not a separate program, and it need not be installed by itself.
In fact, the PVM is just a big loop that iterates through your byte code instructions, one by one, to carry out their operations.
The PVM is the runtime engine of Python; it’s always present as part of the Python system, and it’s the component that truly runs your scripts.
Technically, it’s just the last step of what is called the “Python interpreter.” Figure 2-2 illustrates the runtime structure described here.
Keep in mind that all of this complexity is deliberately hidden from Python programmers.
Byte code compilation is automatic, and the PVM is just part of the Python system that you have installed on your machine.
Again, programmers simply code and run files of statements. ###### Performance implications Readers with a background in fully compiled languages such as C and C++ might notice a few differences in the Python model.
For one thing, there is usually no build or “make” step in Python work: code runs immediately after it is written.
For another, Python byte code is not binary machine code (e.g., instructions for an Intel chip).
Byte code is a Python-specific representation. - And, strictly speaking, byte code is saved only for files that are imported, not for the top-level file of a program. We’ll explore imports in Chapter 3, and again in Part V.
Byte code is also never saved for code typed at the interactive prompt, which is described in Chapter 3. **|** ----- _Figure 2-2.
Python’s traditional runtime execution model: source code you type is translated to byte_ _code, which is then run by the Python Virtual Machine.
Your code is automatically compiled, but then_ _it is interpreted._ This is why some Python code may not run as fast as C or C++ code, as described in Chapter 1—the PVM loop, not the CPU chip, still must interpret the byte code, and byte code instructions require more work than CPU instructions.
On the other hand, unlike in classic interpreters, there is still an internal compile step—Python does not need to reanalyze and reparse each source statement repeatedly.
The net effect is that pure Python code runs at speeds somewhere between those of a traditional compiled language and a traditional interpreted language.
See Chapter 1 for more on Python performance tradeoffs. ###### Development implications Another ramification of Python’s execution model is that there is really no distinction between the development and execution environments.
That is, the systems that compile and execute your source code are really one and the same.
This similarity may have a bit more significance to readers with a background in traditional compiled languages, but in Python, the compiler is always present at runtime and is part of the system that runs programs. This makes for a much more rapid development cycle.
There is no need to precompile and link before execution may begin; simply type and run the code.
This also adds a much more dynamic flavor to the language—it is possible, and often very convenient, for Python programs to construct and execute other Python programs at runtime.
The ``` eval and exec built-ins, for instance, accept and run strings containing Python program ``` code.