The Interactive Prompt

This section gets us started with interactive coding basics. Because it’s our first look at running code, we also cover some preliminaries here, such as setting up a working directory and the system path, so be sure to read this section first if you’re relatively new to programming. This section also explains some conventions used throughout the book, so most readers should probably take at least a quick look here.

Starting an Interactive Session

Perhaps the simplest way to run Python programs is to type them at Python’s interactive command line, sometimes called the interactive prompt. There are a variety of ways to start this command line: in an IDE, from a system console, and so on. Assuming the interpreter is installed as an executable program on your system, the most platform-neutral way to start an interactive interpreter session is usually just to type python at your operating system’s prompt, without any arguments. For example:

% python
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit ...
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

Typing the word “python” at your system shell prompt like this begins an interactive Python session; the “%” character at the start of this listing stands for a generic system prompt in this book—it’s not input that you type yourself. On Windows, a Ctrl-Z gets you out of this session; on Unix, try Ctrl-D instead.

The notion of a system shell prompt is generic, but exactly how you access it varies by platform:

  • On Windows, you can type python in a DOS console window—a program named cmd.exe and usually known as Command Prompt. For more details on starting this program, see this chapter’s sidebar Where Is Command Prompt on Windows?.

  • On Mac OS X, you can start a Python interactive interpreter by double-clicking on Applications→Utilities→Terminal, and then typing python in the window that opens up.

  • On Linux (and other Unixes), you might type this command in a shell or terminal window (for instance, in an xterm or console running a shell such as ksh or csh).

  • Other systems may use similar or platform-specific devices. On handheld devices, for example, you might click the Python icon in the home or application window to launch an interactive session.

On most platforms, you can start the interactive prompt in additional ways that don’t require typing a command, but they vary per platform even more widely:

  • On Windows 7 and earlier, besides typing python in a shell window, you can also begin similar interactive sessions by starting the IDLE GUI (discussed later), or by selecting the “Python (command line)” menu option from the Start button menu for Python, as shown in Figure 2-1 in Chapter 2. Both spawn a Python interactive prompt with the same functionality obtained with a “python” command.

  • On Windows 8, you don’t have a Start button (at least as I write this), but there are other ways to get to the tools described in the prior bullet, including tiles, Search, File Explorer, and the “All apps” interface on the Start screen. See Appendix A for more pointers on this platform.

  • Other platforms have similar ways to start a Python interactive session without typing commands, but they’re too specific to get into here; see your system’s documentation for details.

Anytime you see the >>> prompt, you’re in an interactive Python interpreter session—you can type any Python statement or expression here and run it immediately. We will in a moment, but first we need to get a few startup details sorted out to make sure all readers are set to go.

The System Path

When we typed python in the last section to start an interactive session, we relied on the fact that the system located the Python program for us on its program search path. Depending on your Python version and platform, if you have not set your system’s PATH environment variable to include Python’s install directory, you may need to replace the word “python” with the full path to the Python executable on your machine. On Unix, Linux, and similar, something like /usr/local/bin/python or /usr/bin/python3 will often suffice. On Windows, try typing C:\Python33\python (for version 3.3):

c:\code> c:\python33\python
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit ...
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

Alternatively, you can run a “cd” change-directory command to go to Python’s install directory before typing python—try the cd c:\python33 command on Windows, for example:

c:\code> cd c:\python33
c:\Python33> python
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit ...
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

But you’ll probably want to set your PATH eventually, so a simple “python” suffices. If you don’t know what PATH is or how to set it, see Appendix A—it covers environment variables like this whose usage varies per platform, as well as Python command-line arguments we won’t be using much in this book. The short story for Windows users: see the Advanced settings in the System entry of your Control Panel. If you’re using Python 3.3 and later, this is now automatic on Windows, as the next section explains.

New Windows Options in 3.3: PATH, Launcher

The foregoing section and much of this chapter at large describe the generic state of play for all 2.X and 3.X Pythons prior to version 3.3. Starting with Python 3.3, the Windows installer has an option to automatically add Python 3.3’s directory to your system PATH, if enabled in the installer’s windows. If you use this option, you won’t need to type a directory path or issue a “cd” to run python commands as in the prior section. Be sure to select this option during the install if you want it, as it’s currently disabled by default.

More dramatically, Python 3.3 for Windows ships with and automatically installs the new Windows launcher—a system that comes with new executable programs, py with a console and pyw without, that are placed in directories on your system path, and so may be run out of the box without any PATH configurations, change-directory commands, or directory path prefixes:

c:\code> py
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit ...
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

c:\code> py −2
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] ...
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

c:\code> py −3.1
Python 3.1.4 (default, Jun 12 2011, 14:16:16) [MSC v.1500 64 bit (AMD64)] ...
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z

As shown in the last two commands here, these executables also accept Python version numbers on the command line (and in Unix-style #! lines at the top of scripts, as discussed later), and are associated to open Python files when clicked just like the original python executable—which is still available and works as before, but is somewhat superseded by the launcher’s new programs.

The launcher is a standard part of Python 3.3, and is available standalone for use with other versions. We’ll see more on this new launcher in this and later chapters, including a brief look at its #! line support here. However, because it is of interest only to Windows users, and even for this group is present only in 3.3 or where installed separately, I’ve collected almost all of the details about the launcher in Appendix B.

If you’ll be working on Windows under Python 3.3 or later, I suggest taking a brief detour to that appendix now, as it provides an alternative, and in some ways better, way to run Python command lines and scripts. At a base level, launcher users can type py instead of python in most of the system commands shown in this book, and may avoid some configuration steps. Especially on computers with multiple Python versions, though, the new launcher gives you more explicit control over which Python runs your code.

Where to Run: Code Directories

Now that I’ve started showing you how to run code, I want to say a few words up front about where to run code. To keep things simple, in this chapter and book at large I’m going to be running code from a working directory (a.k.a. folder) I’ve created on my Windows computer called C:\code—a subdirectory at the top of my main drive. That’s where I’ll start most interactive sessions, and where I’ll be both saving and running most script files. This also means the files that examples will create will mostly show up in this directory.

If you’ll be working along, you should probably do something similar before we get started. Here are some pointers if you need help getting set up with a working directory on your computer:

  • On Windows, you can make your working code directory in File Explorer or a Command Prompt window. In File Explorer, look for New Folder, see the File menu, or try a right-click. In Command Prompt, type and run a mkdir command, usually after you cd to your desired parent directory (e.g., cd c\: and mkdir code). Your working directory can be located wherever you like and called whatever you wish, and doesn’t have to be C:\code (I chose this name because it’s short in prompts). But running out of one directory will help you keep track of your work and simplify some tasks. For more Windows hints, see this chapter’s sidebar on Command Prompt, as well as Appendix A.

  • On Unix-based systems (including Mac OS X and Linux), your working directory might be in /usr/home and be created by a mkdir command in a shell window or file explorer GUI specific to your platform, but the same concepts apply. The Cygwin Unix-like system for Windows is similar too, though your directory names may vary (/home and /cygdrive/c are candidates).

You can store your code in Python’s install directory too (e.g., C:\Python33 on Windows) to simplify some command lines before setting PATH, but you probably shouldn’t—this is for Python itself, and your files may not survive a move or uninstall.

Once you’ve made your working directory, always start there to work along with the examples in this book. The prompts in this book that show the directory that I’m running code in will reflect my Windows laptop’s working directory; when you see C:\code> or %, think the location and name of your own directory.

What Not to Type: Prompts and Comments

Speaking of prompts, this book sometimes shows system prompts as a generic %, and sometimes in full C:\code> Windows form. The former is meant to be platform agnostic (and derives from earlier editions’ use of Linux), and the latter is used in Windows-specific contexts. I also add a space after system prompts just for readability in this book. When used, the % character at the start of a system command line stands for the system’s prompt, whatever that may be on your machine. For instance, on my machine % stands for C:\code> in Windows Command Prompt, and just $ in my Cygwn install.

To beginners: don’t type the % character (or the C:\code system prompt it sometimes stands for) you see in this book’s interaction listings yourself—this is text the system prints. Type just the text after these system prompts. Similarly, do not type the >>> and ... characters shown at the start of lines in interpreter interaction listings—these are prompts that Python displays automatically as visual guides for interactive code entry. Type just the text after these Python prompts. For instance, the ... prompt is used for continuation lines in some shells, but doesn’t appear in IDLE, and shows up in some but not all of this book’s listings; don’t type it yourself if it’s absent in your interface.

To help you remember this, user inputs are shown in bold in this book, and prompts are not. In some systems these prompts may differ (for instance, the PyPy performance-focused implementation described in Chapter 2 uses four-character >>>> and ....), but the same rules apply. Also keep in mind that commands typed after these system and Python prompts are meant to be run immediately, and are not generally to be saved in the source files we will be creating; we’ll see why this distinction matters ahead.

In the same vein, you normally don’t need to type text that starts with a # character in listings in this book—as you’ll learn, these are comments, not executable code. Except when # is used to introduce a directive at the top of a script for Unix or the Python 3.3 Windows launcher, you can safely ignore the text that follows it (more on Unix and the launcher later in this chapter and in Appendix B).

Note

If you’re working along, interactive listings will drop most “...” continuation prompts as of Chapter 17 to aid cut-and-paste of larger code such as functions and classes from ebooks or other; until then, paste or type one line at a time and omit the prompts. At least initially, it’s important to type code manually, to get a feel for syntax details and errors. Some examples will be listed either by themselves or in named files available in the book’s examples package (per the preface), and we’ll switch between listing formats often; when in doubt, if you see “>>>”, it means the code is being typed interactively.

Running Code Interactively

With those preliminaries out of the way, let’s move on to typing some actual code. However it’s started, the Python interactive session begins by printing two lines of informational text giving the Python version number and a few hints shown earlier (which I’ll omit from most of this book’s examples to save space), then prompts for input with >>> when it’s waiting for you to type a new Python statement or expression.

When working interactively, the results of your code are displayed below the >>> input lines after you press the Enter key. For instance, here are the results of two Python print statements (print is really a function call in Python 3.X, but not in 2.X, so the parentheses here are required in 3.X only):

% python
>>> print('Hello world!')
Hello world!
>>> print(2 ** 8)
256

There it is—we’ve just run some Python code (were you expecting the Spanish Inquisition?). Don’t worry about the details of the print statements shown here yet; we’ll start digging into syntax in the next chapter. In short, they print a Python string and an integer, as shown by the output lines that appear after each >>> input line (2 ** 8 means 2 raised to the power 8 in Python).

When coding interactively like this, you can type as many Python commands as you like; each is run immediately after it’s entered. Moreover, because the interactive session automatically prints the results of expressions you type, you don’t usually need to say “print” explicitly at this prompt:

>>> lumberjack = 'okay'
>>> lumberjack
'okay'
>>> 2 ** 8
256
>>> ^Z                     # Use Ctrl-D (on Unix) or Ctrl-Z (on Windows) to exit
%

Here, the first line saves a value by assigning it to a variable (lumberjack), which is created by the assignment; and the last two lines typed are expressions (lumberjack and 2 ** 8), whose results are displayed automatically. Again, to exit an interactive session like this and return to your system shell prompt, type Ctrl-D on Unix-like machines, and Ctrl-Z on Windows. In the IDLE GUI discussed later, either type Ctrl-D or simply close the window.

Notice the italicized note about this on the right side of this listing (staring with “#” here). I’ll use these throughout to add remarks about what is being illustrated, but you don’t need to type this text yourself. In fact, just like system and Python prompts, you shouldn’t type this when it’s on a system command line; the “#” part is taken as a comment by Python but may be an error at a system prompt.

Now, we didn’t do much in this session’s code—just typed some Python print and assignment statements, along with a few expressions, which we’ll study in detail later. The main thing to notice is that the interpreter executes the code entered on each line immediately, when the Enter key is pressed.

For example, when we typed the first print statement at the >>> prompt, the output (a Python string) was echoed back right away. There was no need to create a source code file, and no need to run the code through a compiler and linker first, as you’d normally do when using a language such as C or C++. As you’ll see in later chapters, you can also run multiline statements at the interactive prompt; such a statement runs immediately after you’ve entered all of its lines and pressed Enter twice to add a blank line.

Why the Interactive Prompt?

The interactive prompt runs code and echoes results as you go, but it doesn’t save your code in a file. Although this means you won’t do the bulk of your coding in interactive sessions, the interactive prompt turns out to be a great place to both experiment with the language and test program files on the fly.

Experimenting

Because code is executed immediately, the interactive prompt is a perfect place to experiment with the language and will be used often in this book to demonstrate smaller examples. In fact, this is the first rule of thumb to remember: if you’re ever in doubt about how a piece of Python code works, fire up the interactive command line and try it out to see what happens.

For instance, suppose you’re reading a Python program’s code and you come across an expression like 'Spam!' * 8 whose meaning you don’t understand. At this point, you can spend 10 minutes wading through manuals, books, and the Web to try to figure out what the code does, or you can simply run it interactively:

% python
>>> 'Spam!' * 8                                  # Learning by trying
'Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!'

The immediate feedback you receive at the interactive prompt is often the quickest way to deduce what a piece of code does. Here, it’s clear that it does string repetition: in Python * means multiply for numbers, but repeat for strings—it’s like concatenating a string to itself repeatedly (more on strings in Chapter 4).

Chances are good that you won’t break anything by experimenting this way—at least, not yet. To do real damage, like deleting files and running shell commands, you must really try, by importing modules explicitly (you also need to know more about Python’s system interfaces in general before you will become that dangerous!). Straight Python code is almost always safe to run.

For instance, watch what happens when you make a mistake at the interactive prompt:

>>> X                                            # Making mistakes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'X' is not defined

In Python, using a variable before it has been assigned a value is always an error—otherwise, if names were filled in with defaults, some errors might go undetected. This means you must initial counters to zero before you can add to them, must initial lists before extending them, and so on; you don’t declare variables, but they must be assigned before you can fetch their values.

We’ll learn more about that later; the important point here is that you don’t crash Python or your computer when you make a mistake this way. 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 learn more about debugging options in the sidebar Debugging Python Code).

Testing

Besides serving as a tool for experimenting while you’re learning the language, the interactive interpreter is also an ideal place to test code you’ve written in files. You can import your module files interactively and run tests on the tools they define by typing calls at the interactive prompt on the fly.

For instance, 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, with a doubled-up backslash that stands for just one), but you can do the same once you start writing module files of your own:

>>> import os
>>> os.getcwd()                                  # Testing on the fly
'c:\\code'

More generally, the interactive prompt is a place to test program components, regardless of their source—you can import and test functions and classes in your Python files, type calls to linked-in C functions, exercise Java classes under Jython, and more. Partly because of its interactive nature, Python supports an experimental and exploratory programming style you’ll find convenient when getting started. Although Python programmers also test with in-file code (and we’ll learn ways to make this simple later in the book), for many, the interactive prompt is still their first line of testing defense.

Usage Notes: 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 the following 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 Python’s >>> 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 automatically echoed. Remember, you must say print in files, but it’s optional 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. Remember, a leading space generates an error message, so don’t start with a space or tab at the interactive prompt unless it’s nested code.

  • Watch out for prompt changes for compound statements. We won’t meet compound (multiline) statements until Chapter 4 and not in earnest until Chapter 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 GUI interface, lines after the first are instead 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 risk of repeating myself, I’ve received multiple emails from readers who’d gotten burned by the last two points, so they probably merit emphasis. 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. In other words, 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. Reminder: the ... continuation line prompt in the preceding is printed by Python automatically as a visual guide; it may not appear in your interface (e.g., IDLE), and is sometimes omitted by this book, but do not type it yourself if it’s absent.

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 next statement:

>>> for x in 'spam':
...     print(x)              # 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—which brings us to the next section’s topic.