Text
stringlengths
1
9.41k
Instead, you get a meaningful error message pointing out the mistake and the line of code that made it, and you can continue on in your session or script.
In fact, once you get comfortable with Python, its error messages may often provide as much debugging support as you’ll need (you’ll read more on debugging in the sidebar “Debugging Python Code” on page 67). ###### Testing Besides serving as a tool for experimenting while you’re learning the language, the interactive...
You can import your module files interactively and run tests on the tools they define by typing calls at the interactive prompt. For instance, of the following tests a function in a precoded module that ships with Python in its standard library (it prints the name of the directory you’re currently working in), but you...
Partly because of its interactive nature, Python supports an experimental and exploratory programming style you’ll find convenient when getting started. ###### Using the Interactive Prompt Although the interactive prompt is simple to use, there are a few tips that beginners should keep in mind.
I’m including lists of common mistakes like this in this chapter for reference, but they might also spare you from a few headaches if you read them up front: - Type Python commands only.
First of all, remember that you can only type Python code at the Python prompt, not system commands.
There are ways to run system commands from within Python code (e.g., with os.system), but they are not as direct as simply typing the commands themselves. **|** ----- - print **statements are required only in files.
Because the interactive interpreter** automatically prints the results of expressions, you do not need to type complete ``` print statements interactively.
This is a nice feature, but it tends to confuse users ``` when they move on to writing code in files: within a code file, you must use ``` print statements to see your output because expression results are not automati ``` cally echoed.
Remember, you must say print in files, but not interactively. - Don’t indent at the interactive prompt (yet).
When typing Python programs, either interactively or into a text file, be sure to start all your unnested statements in column 1 (that is, all the way to the left).
If you don’t, Python may print a “SyntaxError” message, because blank space to the left of your code is taken to be indentation that groups nested statements.
Until Chapter 10, all statements you write will be unnested, so this includes everything for now. This seems to be a recurring confusion in introductory Python classes.
Remember, a leading space generates an error message. - Watch out for prompt changes for compound statements.
We won’t meet _compound (multiline) statements until Chapter 4, and not in earnest until Chap-_ ter 10, but as a preview, you should know that when typing lines 2 and beyond of a compound statement interactively, the prompt may change.
In the simple shell window interface, the interactive prompt changes to ...
instead of >>> for lines 2 and beyond; in the IDLE interface, lines after the first are automatically indented. You’ll see why this matters in Chapter 10. For now, if you happen to come across a ...
prompt or a blank line when entering your code, it probably means that you’ve somehow confused interactive Python into thinking you’re typing a multiline statement.
Try hitting the Enter key or a Ctrl-C combination to get back to the main prompt. The >>> and ...
prompt strings can also be changed (they are available in the built-in module sys), but I’ll assume they have not been in the book’s example listings. - Terminate compound statements at the interactive prompt with a blank **line.
At the interactive prompt, inserting a blank line (by hitting the Enter key at** the start of a line) is necessary to tell interactive Python that you’re done typing the multiline statement.
That is, you must press Enter twice to make a compound statement run. By contrast, blank lines are not required in files and are simply ignored if present.
If you don’t press Enter twice at the end of a compound statement when working interactively, you’ll appear to be stuck in a limbo state, because the interactive interpreter will do nothing at all—it’s waiting for you to press Enter again! - The interactive prompt runs one statement at a time.
At the interactive prompt, you must run one statement to completion before typing another.
This is natural for simple statements, because pressing the Enter key runs the statement entered. For compound statements, though, remember that you must submit a blank line to terminate the statement and make it run before you can type the next statement. **|** ----- ###### Entering multiline statements At the ri...
I’ll introduce multiline (a.k.a. compound) statements in the next chapter, and we’ll explore their syntax more formally later in this book.
Because their behavior differs slightly in files and at the interactive prompt, though, two cautions are in order here. First, be sure to terminate multiline compound statements like for loops and if tests at the interactive prompt with a blank line.
You must press the Enter key twice, to terminate the whole multiline statement and then make it run. For example (pun not intended...): ``` >>> for x in 'spam': ``` `...
print(x)` _<== Press Enter twice here to make this loop run_ ``` ... ``` You don’t need the blank line after compound statements in a script file, though; this is required only at the interactive prompt.
In a file, blank lines are not required and are simply ignored when present; at the interactive prompt, they terminate multiline statements. Also bear in mind that the interactive prompt runs just one statement at a time: you must press Enter twice to run a loop or other multiline statement before you can type the nex...
print(x)` _<== Need to press Enter twice before a new statement_ ``` ...
print('done') File "<stdin>", line 3 print('done') ^ SyntaxError: invalid syntax ``` This means you can’t cut and paste multiple lines of code into the interactive prompt, unless the code includes blank lines after each compound statement.
Such code is better run in a file—the next section’s topic. ###### System Command Lines and Files Although the interactive prompt is great for experimenting and testing, it has one big disadvantage: programs you type there go away as soon as the Python interpreter executes them.
Because the code you type interactively is never stored in a file, you can’t run it again without retyping it from scratch.
Cut-and-paste and command recall can help some here, but not much, especially when you start writing larger programs.
To cut and paste code from an interactive session, you would have to edit out Python prompts, program outputs, and so on—not exactly a modern software development methodology! **|** ----- To save programs permanently, you need to write your code in files, which are usually known as modules.
Modules are simply text files containing Python statements.
Once coded, you can ask the Python interpreter to execute the statements in such a file any number of times, and in a variety of ways—by system command lines, by file icon clicks, by options in the IDLE user interface, and more.
Regardless of how it is run, Python executes all the code in a module file from top to bottom each time you run the file. Terminology in this domain can vary somewhat.
For instance, module files are often referred to as programs in Python—that is, a program is considered to be a series of precoded statements stored in a file for repeated execution.
Module files that are run directly are also sometimes called scripts—an informal term usually meaning a top-level program file.
Some reserve the term “module” for a file imported from another file. (More on the meaning of “top-level” and imports in a few moments.) Whatever you call them, the next few sections explore ways to run code typed into module files.
In this section, you’ll learn how to run files in the most basic way: by listing their names in a `python command line entered at your computer’s system` prompt.
Though it might seem primitive to some, for many programmers a system shell command-line window, together with a text editor window, constitutes as much of an integrated development environment as they will ever need. ###### A First Script Let’s get started.
Open your favorite text editor (e.g., vi, Notepad, or the IDLE editor), and type the following statements into a new text file named script1.py: _# A first Python script_ ``` import sys # Load a library module print(sys.platform) print(2 ** 100) # Raise 2 to a power x = 'Spam!' print(x * 8) ...
You shouldn’t worry too much about this file’s code, but as a brief description, this file: - Imports a Python module (libraries of additional tools), to fetch the name of the platform - Runs three print function calls, to display the script’s results - Uses a variable named x, created when it’s assigned, to hold...
Comments can show up on lines by themselves, or to the right of code on a line. The text after a # is simply ignored as a human-readable comment and is not considered part of the statement’s syntax.
If you’re copying this code, you can ignore the comments as well.
In this book, we usually use a different formatting style to make comments more visually distinctive, but they’ll appear as normal text in your code. Again, don’t focus on the syntax of the code in this file for now; we’ll learn about all of it later.
The main point to notice is that you’ve typed this code into a file, rather than at the interactive prompt.
In the process, you’ve coded a fully functional Python script. Notice that the module file is called script1.py.
As for all top-level files, it could also be called simply script, but files of code you want to import into a client have to end with a .py suffix. We’ll study imports later in this chapter.
Because you may want to import them in the future, it’s a good idea to use .py suffixes for most Python files that you code.
Also, some text editors detect Python files by their .py suffix; if the suffix is not present, you may not get features like syntax colorization and automatic indentation. ###### Running Files with Command Lines Once you’ve saved this text file, you can ask Python to run it by listing its full filename as the first a...
Remember to replace “python” with a full directory path, as before, if your ``` PATH setting is not configured. ``` If all works as planned, this shell command makes Python run the code in this file line by line, and you will see the output of the script’s three print statements—the name of the underlying platform, 2 ...
We’ll talk about debugging options in the sidebar “Debugging Python Code” on page 67, but at this point in the book your best bet is probably rote imitation. Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies.
For instance, you can route the output of a Python script to a file to save it for later use or inspection by using special shell syntax: ``` % python script1.py > saveit.txt ``` **|** ----- In this case, the three output lines shown in the prior run are stored in the file _saveit.txt instead of being printed.
This is generally known as_ _stream redirection; it_ works for input and output text and is available on Windows and Unix-like systems. It also has little to do with Python (Python simply supports it), so we will skip further details on shell redirection syntax here. If you are working on a Windows platform, this exam...
Because newer Windows systems use the Windows Registry to find a program with which to run a file, you don’t need to name “python” on the command line explicitly to run a .py file.
The prior command, for example, could be simplified to this on most Windows machines: ``` D:\temp> script1.py ``` Finally, remember to give the full path to your script file if it lives in a different directory from the one in which you are working.
For example, the following system command line, run from D:\other, assumes Python is in your system path but runs a file located elsewhere: ``` D:\other> python c:\code\otherscript.py ``` If your PATH doesn’t include Python’s directory, and neither Python nor your script file is in the directory you’re working in, u...
For newcomers, though, here are a few pointers about common beginner traps that might help you avoid some frustration: **|** ----- - Beware of automatic extensions on Windows.
If you use the Notepad program to code program files on Windows, be careful to pick the type All Files when it comes time to save your file, and give the file a .py suffix explicitly.
Otherwise, Notepad will save your file with a .txt extension (e.g., as script1.py.txt), making it difficult to run in some launching schemes. Worse, Windows hides file extensions by default, so unless you have changed your view options you may not even notice that you’ve coded a text file and not a Python file.
The file’s icon may give this away—if it doesn’t have a snake on it, you may have trouble.
Uncolored code in IDLE and files that open to edit instead of run when clicked are other symptoms of this problem. Microsoft Word similarly adds a .doc extension by default; much worse, it adds formatting characters that are not legal Python syntax.
As a rule of thumb, always pick All Files when saving under Windows, or use a more programmer-friendly text editor such as IDLE.
IDLE does not even add a .py suffix automatically—a feature programmers tend to like, but users do not. - Use file extensions and directory paths at system prompts, but not for im**ports.
Don’t forget to type the full name of your file in system command lines—** that is, use python script1.py rather than python script1.
By contrast, Python’s ``` import statements, which we’ll meet later in this chapter, omit both the .py file ``` suffix and the directory path (e.g., `import script1).
This may seem trivial, but` confusing these two is a common mistake. At the system prompt, you are in a system shell, not Python, so Python’s module file search rules do not apply.
Because of that, you must include both the .py extension and, if necessary, the full directory path leading to the file you wish to run. For instance, to run a file that resides in a different directory from the one in which you are working, you would typically list its full path (e.g., ``` python d:\tests\spam.py).
Within Python code, however, you can just say import spam and rely on the Python module search path to locate your file, as ``` described later. - Use `print` **statements in files.
Yes, we’ve already been over this, but it is such a** common mistake that it’s worth repeating at least once here.
Unlike in interactive coding, you generally must use print statements to see output from program files. If you don’t see any output, make sure you’ve said “print” in your file.
Again, though, print statements are not required in an interactive session, since Python automatically echoes expression results; prints don’t hurt here, but are superfluous extra typing. **|** ----- ###### Unix Executable Scripts (#!) If you are going to use Python on a Unix, Linux, or Unix-like system, you can a...
Such files are usually called executable scripts. In simple terms, Unix-style executable scripts are just normal text files containing Python statements, but with two special properties: - Their first line is special.
Scripts usually start with a line that begins with the characters #!
(often called “hash bang”), followed by the path to the Python interpreter on your machine. - They usually have executable privileges.
Script files are usually marked as executable to tell the operating system that they may be run as top-level programs. On Unix systems, a command such as chmod +x `file.py usually does the trick.` Let’s look at an example for Unix-like systems.
Use your text editor again to create a file of Python code called brian: ``` #!/usr/local/bin/python print('The Bright Side ' + 'of Life...') # + means concatenate for strings ``` The special line at the top of the file tells the system where the Python interpreter lives. Technically, the first line is a Python...
As mentioned earlier, all comments in Python programs start with a # and span to the end of the line; they are a place to insert extra information for human readers of your code.
But when a comment such as the first line in this file appears, it’s special because the operating system uses it to find an interpreter for running the program code in the rest of the file. Also, note that this file is called simply brian, without the .py suffix used for the module file earlier.
Adding a .py to the name wouldn’t hurt (and might help you remember that this is a Python program file), but because you don’t plan on letting other modules import the code in this file, the name of the file is irrelevant.
If you give the file executable privileges with a chmod +x brian shell command, you can run it from the operating system shell as though it were a binary program: ``` % brian The Bright Side of Life... ``` A note for Windows users: the method described here is a Unix trick, and it may not work on your platform.
Not to worry; just use the basic command-line technique explored earlier.
List the file’s name on an explicit python command line:[*] - As we discussed when exploring command lines, modern Windows versions also let you type just the name of a .py file at the system command line—they use the Registry to determine that the file should be opened with Python (e.g., typing `brian.py is equivalen...
This command-line mode is` similar in spirit to the Unix `#!, though it is system-wide on Windows, not per-file. Note that some` _programs may actually interpret and use a first #!
line on Windows much like on Unix, but the DOS system_ shell on Windows simply ignores it. **|** ----- ``` C:\misc> python brian The Bright Side of Life... ``` In this case, you don’t need the special #!
comment at the top (although Python just ignores it if it’s present), and the file doesn’t need to be given executable privileges.
In fact, if you want to run files portably between Unix and Microsoft Windows, your life will probably be simpler if you always use the basic command-line approach, not Unixstyle scripts, to launch programs. ###### The Unix env Lookup Trick On some Unix systems, you can avoid hardcoding the path to the Python interpr...
This scheme can be more portable, as you` don’t need to hardcode a Python install path in the first line of all your scripts. Provided you have access to env everywhere, your scripts will run no matter where Python lives on your system—you need only change the `PATH environment variable` settings across platforms, not...
Of course, this assumes that _env lives in the same place everywhere (on some machines, it may be_ in /sbin, /bin, or elsewhere); if not, all portability bets are off! ###### Clicking File Icons On Windows, the Registry makes opening files with icon clicks easy.
Python automatically registers itself to be the program that opens Python program files when they are clicked.
Because of that, it is possible to launch the Python programs you write by simply clicking (or double-clicking) on their file icons with your mouse cursor. On non-Windows systems, you will probably be able to perform a similar trick, but the icons, file explorer, navigation schemes, and more may differ slightly.
On some Unix systems, for instance, you may need to register the .py extension with your file explorer GUI, make your script executable using the #!
trick discussed in the previous section, or associate the file MIME type with an application or command by editing files, installing programs, or using other tools.
See your file explorer’s documentation for more details if clicks do not work correctly right off the bat. ###### Clicking Icons on Windows To illustrate, let’s keep using the script we wrote earlier, script1.py, repeated here to minimize page flipping: **|** ----- _# A first Python script_ ``` import sys ...
If you find this file’s icon—for instance, by selecting Computer (or My Computer in XP) in your Start menu and working your way down on the C drive on Windows—you will get the file explorer picture captured in Figure 3-1 (Windows Vista is being used here).
Python source files show up with white backgrounds on Windows, and byte code files show up with black backgrounds.