2. Getting started

Chapter 2. Getting started

This chapter guides you through downloading, installing, and starting up Python and IDLE, an integrated development environment for Python. At this writing, Python 3.6 is the most current version, and 3.7 is under development. After years of refinement, Python 3 is the first version of the language that isn’t fully backward-compatible with earlier versions, so be sure to get a version of Python 3. It should be several years before another such dramatic change occurs, and any future enhancements will be developed with concern to avoid affecting an already-significant existing code base. Therefore, the material presented after this chapter isn’t likely to become dated any time soon.

2.1. Installing Python

Installing Python is a simple matter, regardless of which platform you’re using. The first step is to obtain a recent distribution for your machine; the most recent one can always be found at www.python.org. This book is based on Python 3.6. If you have Python 3.5 or even 3.7, that’s fine. In fact, you should have little trouble using most of this book with any version of Python 3.

HAVING MORE THAN ONE VERSION OF PYTHON

You may already have an earlier version of Python installed on your machine. Many Linux distributions and macOS come with Python 2.x as part of the operating system. Because Python 3 isn’t completely compatible with Python 2, it’s reasonable to wonder whether installing both versions on the same computer will cause a conflict.

There’s no need to worry; you can have multiple versions of Python on the same computer. In the case of UNIX-based systems like OS X and Linux, Python 3 installs alongside the older version and doesn’t replace it. When your system looks for “python,” it still finds the one it expects, and when you want to access Python 3, you can run python3 or idle. In Windows, the different versions are installed in separate locations and have separate menu entries.

Some basic platform-specific descriptions for the Python installation are given next. The specifics can vary quite a bit depending on your platform, so be sure to read the instructions on the download pages and for the various versions. You’re probably familiar with installing software on your particular machine, so I’ll keep these descriptions short:

  • Microsoft Windows— Python can be installed in most versions of Windows by using the Python installer program, currently called python-3.6.1.exe. Download it, execute it, and follow the installer’s prompts. You may need to be logged in as administrator to run the install. If you’re on a network and don’t have the administrator password, ask your system administrator to do the installation for you.

  • Macintosh— You need to get a version of Python 3 that matches your OS X version and your processor. After you determine the correct version, download the disk image file, double-click to mount it, and run the installer inside. The OS X installer sets up everything automatically, and Python 3 will be in a subfolder inside the Applications folder, labeled with the version number. macOS ships with various versions of Python as part of the system, but you don’t need to worry about that; Python 3 will be installed in addition to the system version. If you have brew installed, you can also use it to install Python by using the command brew install python3. You can find more information about using Python on OS X by following the links on the Python home page.

  • Linux/UNIX— Most Linux distributions come with Python installed. But the versions of Python vary, and the version of Python installed may not be version 3; for this book, you need to be sure you have the Python 3 packages installed. It’s also possible that IDLE isn’t installed by default and that you’ll need to install that package separately. Although it’s also possible to build Python 3 from the source code available on the www.python.org website, additional libraries are needed, and the process isn’t for novices. If a precompiled version of Python exists for your distribution of Linux, I recommend using that. Use the software management system for your distribution to locate and install the correct packages for Python 3 and IDLE. Versions are also available for running Python under many other operating systems. See www.python.org for a current list of supported platforms and specifics on installation.

ANACONDA: AN ALTERNATIVE PYTHON DISTRIBUTION

In addition to the distribution of Python that you can get directly from Python.org, a distribution called Anaconda is gaining popularity, particularly among scientific and data science users. Anaconda is an open data science platform with Python at its core. When you install Anaconda, you get not only Python, but also the R language and a generous collection of preinstalled data science packages, and you can add many more by using the included conda package manager. You can also install miniconda, which includes only Python and conda, and then add the packages you need.

You can get Anaconda or miniconda from www.anaconda.com/download/. Download the Python 3 version of the installer that matches your operating system, and run it according to the instructions. When that’s done, you’ll have a full version of Python on your machine.

Particularly if your primary interest is in data science, you may find Anaconda to be a quicker and easier way to get up and running with Python.

2.2. Basic interactive mode and IDLE

You have two built-in options for obtaining interactive access to the Python interpreter: the original basic (command-line) mode and IDLE. IDLE is available on many platforms, including Windows, Mac, and Linux, but it may not be available on others. You may need to do more work and install additional software packages to get IDLE running, but doing so will be worthwhile because IDLE offers a somewhat smoother experience than the basic interactive mode. On the other hand, even if you normally use IDLE, at times you’ll likely want to fire up the basic mode. You should be familiar enough to start and use either one.

2.2.1. The basic interactive mode

The basic interactive mode is a rather primitive environment, but the interactive examples in this book are generally small. Later in this book, you learn how to easily bring code you’ve placed in a file into your session (by using the module mechanism). Here’s how to start a basic session on Windows, macOS, and UNIX:

  • Starting a basic session on Windows— For version 3.x of Python, you navigate to the Python 3.6 (32-bit) entry on the Python 3.6 submenu of the Programs folder on the Start menu, and click it. Alternatively, you can directly find the Python.exe executable (for example, in C:\Users\myuser\AppData\Local\Programs\Python \Python35-32) and double-click it. Doing so brings up the window shown in figure 2.1.

  • Starting a basic session on macOS— Open a terminal window and type python3. If you get a “Command not found” error, run the Update Shell Profile command script located in the Python3 subfolder in the Applications folder.

  • Starting a basic session on UNIX— Type python3 at a command prompt. A version message similar to the one shown in figure 2.1 followed by the Python prompt >>> appears in the current window.

Figure 2.1. Basic interactive mode on Windows 10

EXITING THE INTERACTIVE SHELL

To exit from a basic session, press Ctrl-Z (if you’re on Windows) or Ctrl-D (if you’re on Linux or UNIX), or type exit() at a command prompt.

Most platforms have a command-line-editing and command-history mechanism. You can use the up and down arrows, as well as the Home, End, Page Up, and Page Down keys, to scroll through past entries and repeat them by pressing the Enter key. This is all you need to work your way through this book as you’re learning Python. Another option is to use the excellent Python mode available for Emacs, which, among other things, provides access to the interactive mode of Python through an integrated shell buffer.

2.2.2. The IDLE integrated development environment

IDLE is the built-in development environment for Python. Its name is based on the acronym for integrated development environment (though of course, it may have been influenced by the last name of a certain cast member of a particular British television show). IDLE combines an interactive interpreter with code editing and debugging tools to give you one-stop shopping as far as creating Python code is concerned. IDLE’s various tools make it an attractive place to start as you learn Python. This is how you run IDLE on Windows, macOS, and Linux:

  • Starting IDLE on Windows—For version 3.6 of Python, you navigate to the IDLE (Python GUI) entry of the Python 3.6 submenu of the All apps folder of your Windows menu, and click it. Doing so brings up the window shown in figure 2.2.

  • Starting IDLE on macOS—Navigate to the Python 3.x subfolder in the Applications folder, and run IDLE from there.

  • Starting IDLE on Linux or UNIX—Type idle3 at a command prompt. This brings up a window similar to the one shown in figure 2.2. If you installed IDLE through your distribution’s package manager, there should also be a menu entry for IDLE on the Programming submenu or something similar.

Figure 2.2. IDLE on Windows

2.2.3. Choosing between basic interactive mode and IDLE

Which should you use: IDLE or the basic shell window? To begin, use either IDLE or the Python shell window. Both have all you need to work through the code examples in this book until you reach chapter 10. From there, I cover writing your own modules, and IDLE will be a convenient way to create and edit files. But if you have a strong preference for another editor, you may find that a basic shell window and your favorite editor serve you just as well. If you don’t have any strong editor preferences, I suggest using IDLE from the beginning.

2.3. Using IDLE’s Python shell window

The Python shell window (figure 2.3) opens when you fire up IDLE. It provides automatic indentation and colors your code as you type it in, based on Python syntax types.

Figure 2.3. Using the Python shell in IDLE. Code is automatically colored (based on Python syntax) as it’s typed in. Placing the cursor on any previous command and pressing the Enter key moves the command and the cursor to the bottom, where you can edit the command and then press Enter to send it to the interpreter. Placing the cursor at the bottom, you can toggle up and down through the history of previous commands by pressing Alt-P and Alt-N. When you have the command you want, edit it as desired and press Enter, and it will be sent to the interpreter.

You can move around the buffer by using the mouse, the arrow keys, the Page Up and Page Down keys, and/or some of the standard Emacs key bindings. Check the Help menu for the details.

Everything in your session is buffered. You can scroll or search up, place the cursor on any line, and press Enter (creating a hard return), and that line will be copied to the bottom of the screen, where you can edit it and then send it to the interpreter by pressing the Enter key again. Or, leaving the cursor at the bottom, you can toggle up and down through the previously entered commands by pressing Alt-P and Alt-N, which successively bring copies of the lines to the bottom. When you have the one you want, you can again edit it and then send it to the interpreter by pressing the Enter key. You can see a list of possible completions with Python keywords or user-defined values by pressing Tab.

If you ever find yourself in a situation where you seem to be hung and can’t get a new prompt, the interpreter is likely in a state where it’s waiting for you to enter something specific. Pressing Ctrl-C sends an interrupt and should get you back to a prompt. It can also be used to interrupt any running command. To exit IDLE, choose Exit from the File menu.

The Edit menu is the one you’ll likely be using most to begin with. As with any of the other menus, you can tear it off by double-clicking the dotted line at its top and leaving it up beside your window.

2.4. Hello, world

Regardless of how you’re accessing Python’s interactive mode, you should see a prompt consisting of three angle braces: >>>. This prompt is the Python command prompt, and it indicates that you can type in a command to be executed or an expression to be evaluated. Start with the obligatory “Hello, World” program, which is a one-liner in Python (ending each line you type with a hard return):

>>> print("Hello, World")
Hello, World

copy

Here, I entered the print function at the command prompt, and the result appeared on the screen. Executing the print function causes its argument to be printed to the standard output—usually, the screen. If the command had been executed while Python was running a Python program from a file, exactly the same thing would have happened: “Hello, World” would have been printed to the screen.

Congratulations! You’ve just written your first Python program, and I haven’t even started talking about the language.

2.5. Using the interactive prompt to explore Python

Whether you’re in IDLE or at a standard interactive prompt, a couple of handy tools can help you explore Python. The first is the help() function, which has two modes. You can enter help() at the prompt to enter the help system, where you can get help on modules, keywords, or topics. When you’re in the help system, you see a help> prompt, and you can enter a module name, such as math or some other topic, to browse Python’s documentation on that topic.

Usually, it’s more convenient to use help() in a more targeted way. Entering a type or variable name as a parameter for help() gives you an immediate display of that type’s documentation:

>>> x = 2
>>> help(x)
Help on int object:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the...
(continues with the documentation for an int)

copy

Using help() in this way is handy for checking the exact syntax of a method or the behavior of an object.

The help() function is part of the pydoc library, which has several options for accessing the documentation built into Python libraries. Because every Python installation comes with complete documentation, you can have all of the official documentation at your fingertips, even if you aren’t online. See appendix A for more information on accessing Python’s documentation.

The other useful function is dir(), which lists the objects in a particular namespace. Used with no parameters, it lists the current globals, but it can also list objects for a module or even a type:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
     '__package__', '__spec__', 'x']
>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',
     '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__',
     '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',
     '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__',
     '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__',
     '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__',
     '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__',
     '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
     '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__',
     '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
     '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
     '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length',
     'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real',
     'to_bytes']
>>>

copy

dir() is useful for finding out what methods and data are defined, for reminding yourself at a glance of all the members that belong to an object or module, and for debugging because you can see what is defined where.

Unlike dir, both globals and locals show the values associated with the objects. In the current situation, both functions return the same thing, so we have only shown the output from globals():

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
     <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
     '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
     'x': 2}

copy

Unlike dir, both globals and locals show the values associated with the objects. You find out more about both of these functions in chapter 10; for now, it’s enough to be aware that you have several options for examining what’s going on within a Python session.

Summary

  • Installing Python 3 on Windows systems is as simple as downloading the latest installer from www.python.org and running it. Installation on Linux, UNIX, and Mac systems will vary.

  • Refer to installation instructions on the Python website, and use your system’s software package installer where possible.

  • Another installation option is to install the Anaconda (or miniconda) distribution from https://www.anaconda.com/download/.

  • After you’ve installed Python, you can use either the basic interactive shell (and later, your favorite editor) or the IDLE integrated development environment.

Last updated