Book Image

The Python Apprentice

By : Robert Smallshire, Austin Bingham
Book Image

The Python Apprentice

By: Robert Smallshire, Austin Bingham

Overview of this book

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it’s not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.
Table of Contents (21 chapters)
Title Page
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
12
Afterword – Just the Beginning

Preface

Welcome to The Python Apprentice! Our goal with this book is to give you a practical and thorough introduction to the Python programming language, providing you with the tools and insight you need to be a productive member of nearly any Python project. Python is a big language, and its not our intention with this book to cover everything there is to know. Rather we want to help you build solid foundations, orient you in the sometimes bewildering universe of Python, and put you in a position to direct your own continued learning.

This book is primarily aimed at people with some experience programming in another language. If you're currently programming in any of the mainstream imperative or object-oriented languages like C++, C#, or Java, then you'll have the background you need to get the most out of this book. If you have experience in other types of languages – for example, functional or actor-based – then you may have a bit steeper learning curve with Python, but you won't encounter any serious difficulties. Most programmers find Python very approachable and intuitive, and with just a little practice they quickly become comfortable with it.

On the other hand, if you don't have any experience with programming this book may be a bit daunting. You'll be learning not just a programming language but many of the topics and issues common to all languages at the same time. And to be fair, we don't spend a lot of time trying to explain these areas of "assumed knowledge". This doesn't mean you can't learn from this book! It just means that you might have to work a bit harder, read sections multiple times, and perhaps get guidance from others. The reward for this effort, though, is that you'll start to develop the knowledge and instincts for approaching other languages, and this is a critical skill for the professional programmer.

In this first chapter we'll take a quick tour of the Python language. We'll cover what Python is (hint: it's more than just a language!), take a look at how it was – and still is – developed, and get a sense of what makes it so appealing to so many programmers. We'll also give a brief preview of how the rest of the book is structured.

Python Promo

To start with, what's so great about Python? Why do you want to learn it? There are lots of good answers to those questions. One is that Python is powerful. The Python language is expressive and productive, it comes with a great standard library, and it's the center of a huge universe of wonderful third-party libraries. With Python you can build everything from simple scripts to complex applications, you can do it quickly, you can do it safely, and you can do it with fewer lines of code than you might think possible.

But that's just one part of what makes Python great. Another is that Python is wonderfully open. Its open-source, so you can get to know every aspect of it if you want. At the same time, Python is hugely popular and has a great community to support you when you run into trouble. This combination of openness and large userbase means that almost anyone – from casual programmers to professional software developers – can engage with the language at the level they need.

Another benefit of a large user base is that Python is showing up in more and more places. You may be wanting learn Python simply because it's the language of some technology you want to use, and this is not surprising – many of the most popular web and scientific packages in the world are written in Python.

But for many people those reasons take back-seat to something more important: Python is fun! Python's expressive, readable style, quick edit-and-run development cycle, and "batteries included" philosophy mean that you can sit down and enjoy writing code rather than fighting compilers and thorny syntax. And Python will grow with you. As your experiments become prototypes and your prototypes become products, Python makes the experience of writing software not just easier but truly enjoyable.

In the words of Randall Munroe, "Come join us! Programming is fun again!"

Overview

This book comprises 10 chapters (not including this one). The chapters build on one another, so unless you've already had some exposure to Python you'll need to follow them in order. We'll start with getting Python installed into your system and orienting you a bit.

We'll then cover language elements, features, idioms, and libraries, all driven by working examples that you'll be able to build along with the text. We're firm believers that you'll learn more by doing than by just reading, so we encourage you to run the examples yourself.

By the end of the book you'll know the fundamentals of the Python language. You'll also know how to use third-party libraries, and you'll know the basics of developing them yourself. We'll even cover the basics of testing so that you can ensure and maintain the quality of the code you develop.

The chapters are:

  1. Getting started: We go through installing Python, look at some of the basic Python tools, and cover the core elements of the language and syntax.

  2. Strings and Collections: We look at some of the fundamental complex data types: strings, byte sequences, lists, and dictionaries.

  3. Modularity: We look at the tools Python has for structuring your code, such as functions and modules.

  4. Built-in types and the object model: We examine Python's type system and object system in detail, and we develop a strong sense of Python’s reference semantics.

  5. Exploring Built-in Collection Types: We go into more depth on some of the Python collection types, as well as introduce a few more.

  6. Exceptions: We learn about Python's exception-handling system and the central role that exceptions play in the language.

  7. Comprehensions, iterables, and generators: We explore the elegant, pervasive, and powerful sequence-oriented parts of Python such as comprehensions and generator functions.

  8. Defining new types with classes: We cover developing your own complex data types in Python using classes to support object-oriented programming.

  9. Files and Resource Management: We look at how to work with files in Python, and we cover the tools Python has for Resource Management.

  10. Unit testing with the Python standard library: We show you how to use Python's unittest package to produce defect-free code that works as expected.

What is Python?

It's a programming language!

So what is Python? Simply put, Python is a programming language. It was initially developed by Guido van Rossum in the late 1980's in the Netherlands. Guido continues to be actively involved in guiding the development and evolution of the language, so much so that he's been given the title "Benevolent Dictator for Life", or, more commonly, BDFL. Python is developed as an open-source project and is free to download and use as you wish. The non-profit Python Software Foundation manages Python's intellectual property, plays a strong role in promoting the language, and in some cases funds its development.

On a technical level, Python is a strongly typed language. This means that every object in the language has a definite type, and there's generally no way to circumvent that type. At the same time, Python is dynamically typed, meaning that there's no type-checking of your code prior to running it. This is in contrast to statically typed languages like C++ or Java where a compiler does a lot of type-checking for you, rejecting programs which misuse objects. Ultimately, the best description of the Python type system is that it uses duck-typing where an object's suitability for a context is only determined at runtime. We'll cover this in more detail in Chapter 8, Defining new types with classes.

Python is a general-purpose programming language. It's not intended for use in any particular domain or environment, but instead can be fruitfully used for a wide variety of tasks. There are, of course, some areas where it's less suitable than others – for example in extremely time-sensitive or memory-constrained environments – but for the most part Python is as flexible and adaptable as many modern programming language, and more so than most.

Python is an interpreted language. This is a bit of a misstatement, technically, because Python is normally compiled into a form of byte-code before it's executed. However, this compilation happens invisibly, and the experience of using Python is normally one of immediately executing code without a noticeable compilation phase. This lack of an interruption between editing and running is one of the great joys of working with Python.

The syntax of Python is designed to be clear, readable, and expressive. Unlike many popular languages, Python uses white-space to delimit code blocks, and in the process does away with reams of unnecessary parentheses while enforcing a universal layout. This means that all Python code looks alike in important ways, and you can learn to read Python very quickly. At the same time, Python's expressive syntax means that you can get a lot of meaning into a single line of code. This expressive, highly-readable code means that Python maintenance is relatively easy.

There are multiple implementations of the Python language. The original – and still by far the most common – implementation is written in C. This version is commonly referred to as CPython. When someone talks about "running Python", it's normally safe to assume that they are talking about CPython, and this is the implementation that we'll be using for this book.

Other implementations of Python include:

  • Jython, written to target the Java Virtual Machine

  • IronPython, written to target the .NET platform

  • PyPy, written (somewhat circularly) in a language called RPython which is designed for developing dynamic languages like Python

These implementations generally trail behind CPython, which is considered to be the "standard" for the language. Much of what you will learn in this book will apply to all of these implementations.

Versions of the Python language

There are two important versions of the Python language in common use right now: Python 2 and Python 3. These two versions represent changes in some key elements of the language, and code written for one will not generally work for the other unless you take special precautions. Python 2 is older and more well-established than Python 3, but Python 3 addresses some known shortcomings in the older version. Python 3 is the definite future of Python, and you should use it if at all possible.

While there are some critical differences between Python 2 and 3, most of the fundamentals of the two version are the same. If you learn one, most of what you know transfers cleanly to the other. In this book we'll be teaching Python 3, but we'll point out important differences between the versions when necessary.

It's a standard library!

Beyond being a programming language, Python comes with a powerful and broad standard library. Part of the Python philosophy is "batteries included", meaning that you can use Python for many complex, real-world tasks out-of-the box, with no need to install third-party packages. This is not only extremely convenient, but it means that it's easier to get started learning Python by using interesting, engaging examples – something we aim for in this book!

Another great effect of the "batteries included" approach is that it means that many scripts – even non-trivial ones – can be run immediately on any Python installation. This removes a common, annoying barrier to installing software that you can face with other languages.

The standard library has a generally high level of good documentation. The APIs are well documented, and the modules often have good narrative descriptions with quick start guides, best practice information, and so forth. The standard library documentation is always available online, and you can also install it locally if you want to.

Since the standard library is such an important part of Python, we'll be covering parts of it throughout this book. Even so, we won't be covering more than a small fraction of it, so you're encouraged to explore it on your own.

It's a philosophy

Finally, no description of Python would be complete with mentioning that, to many people, Python represents a philosophy for writing code. Principles of clarity and readability are part of what it means to write correct or pythonic code. It's not always clear what pythonic means in all circumstances, and sometimes there may be no single correct way to write something. But the fact that the Python community is concerned about issues like simplicity, readability, and explicitness means that Python code tends to be more…well…beautiful!

Many of Python's principles are embodied in the so-called Zen of Python. The "zen" isn't a hard-and-fast set of rules, but rather a set of guidelines or touchstones to keep in mind when coding. When you find yourself trying to decide between several courses of action, these principles can often give you a nudge in the right direction. We'll be highlighting elements from the "Zen of Python" throughout this book.

The journey of a thousand miles…

We think Python is a great language, and we're excited to help you get started with it. By the time you get through this book, you will be able to write substantial Python programs, and you'll be able to read even more complex ones. More importantly, you'll have the foundation you need to go out and discover all of the more advanced topics in the language, and hopefully we'll get you excited enough about Python to actually do so. Python is a big language with a huge eco-system of software built in and around it, and it can be a real adventure to discover everything it has to offer.

Welcome to Python!

Though more and more projects are starting to be "primarily Python 3" or even "Python 3 only".

This book came about by circuitous means. In 2013, when we incorporated our Norway-based sofware consultancy and training business Sixty North, we were courted by Pluralsight, a publisher of online video training material, to produce Python training videos for the rapidly growing MOOC market. At the time, we had no experience of producing video training material, but we were sure we wanted to carefully structure our introductory Python content to respect certain constraints. For example, we wanted an absolute minimum of forward references since those would be very inconvenient for our viewers. We're both men of words who live by Turing Award winner Leslie Lamport's maxim "If you're thinking without writing you only think you're thinking", so it was natural for us to attack video course production by first writing a script.

In short order our online video course was written, recorded, and published by Pluralsight as Python Fundamentals, to a hugely positive reception which has sustained for several years now. From the earliest days we had in mind that the script could form the basis of a book, although it's fair to say we underestimated the effort required to transform the content from a good script into a better book.

The Python Apprentice is the result of that transformation. It can be used either as a standalone Python tutorial, or as the companion volume to our video course, depending on which style of learning suits you best. The Python Apprentice is the first in a trilogy of three books, comprising in addition The Python Journeyman and The Python Master. The two later books correspond to our subsequent Pluralsight courses Python – Beyond the Basics and Advanced Python (coming soon!).

Errata and Suggestions

All the material in this book has been thoroughly reviewed and tested; nevertheless, it's inevitable that some mistakes have crept in. If you do spot a mistake, we'd really appreciate it if you'd let us know via the Leanpub Python Apprentice Discussion page so we can make amends and deploy a new version.

Conventions Used in This Book

Code examples in this book are shown in a lucida console text:

>>> def square(x):
...     return x * x
...

Some of our examples show code saved in files, and others — such as the one above — are from interactive Python sessions. In such interactive cases, we include the prompts from the Python session such as the triple-arrow >>> and triple-dot ... prompts. You don't need to type these arrows or dots. Similarly, for operating system shell-commands we will use a dollar prompt $ for Linux, macOS and other Unixes, or where the particular operating system is unimportant for the task at hand:

$ python3 words.py

In this case, you don't need to type the $ character.

For Windows-specific commands we will use a leading greater-than prompt:

> python words.py

Again, there's no need to type the > character. For code blocks which need to be placed in a file, rather than entered interactively, we show code without any leading prompts:

def write_sequence(filename, num):
    """Write Recaman's sequence to a text file."""
    with open(filename, mode='wt', encoding='utf-8') as f:
        f.writelines("{0}\n".format(r)
            for r in islice(sequence(), num + 1))

We've worked hard to make sure that our lines of code are short enough so that each single logical line of code corresponds to a single physical line of code in your book. However, the vagaries of publishing e-books to different devices and the very genuine need for occasional long lines of code mean we can't guarantee that lines don't wrap. What we can guarantee, however, is that where a line does wrap, the publisher has inserted a backslash character \ in the final column. You need to use your judgement to determine whether this character is legitimate part of the code or has been added by the e-book platform.

>>> print("This is a single line of code which is very long. Too long, in fact, to fit on a single physical line of code in the book.")

If you see a backslash at the end of the line within the above quoted string, it is not part of the code, and should not be entered.

Occasionally, we'll number lines of code so we can refer to them easily from the narrative next. These line numbers should not be entered as part of the code. Numbered code blocks look like this:

def write_grayscale(filename, pixels):
    height = len(pixels)
    width = len(pixels[0])

    with open(filename, 'wb') as bmp:
        # BMP Header
        bmp.write(b'BM')

        # The next four bytes hold the filesize as a 32-bit
        # little-endian integer. Zero placeholder for now.
        size_bookmark = bmp.tell()
        bmp.write(b'\x00\x00\x00\x00')

Sometimes we need to present code snippets which are incomplete. Usually this is for brevity where we are adding code to an existing block, and where we want to be clear about the block structure without repeating all existing contents of the block. In such cases we use a Python comment containing three dots # ... to indicate the elided code:

class Flight:

    # ...

    def make_boarding_cards(self, card_printer):
        for passenger, seat in sorted(self._passenger_seats()):
            card_printer(passenger, seat, self.number(),     
                self.aircraft_model())

Here it is implied that some other code already exists within the Flight class block before the make_boarding_cards() function.

Finally, within the text of the book, when we are referring to an identifier which is also a function we will use the identifier with empty parentheses, just as we did with make_boarding_cards() in the preceding paragraph.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/The-Python-Apprentice. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ThePythonApprentice_ColorImages.pdf.